I am building a small prototype, and have the following problem:

我正在构建一个小型原型,并存在以下问题:

I am trying to communicate between client-side jQuery, and server-side node.js; when I make a jQuery ajax request to my node.js code, it just gives me the code, not the output of the code.

我试图在客户端jQuery和服务器端node.js之间进行通信;当我向我的node.js代码发出jQuery ajax请求时,它只是给我代码,而不是代码的输出。

What am I doing wrong?

我究竟做错了什么?

Part of client.js:

client.js的一部分:

$.ajax({url      : './../includes/get_data.js', 
        success  : function(data) {
          alert('success!');
        },
        error    : function(data) {
          alert('error!');
        }
});  

get_data.js:

var fs = require('fs');

console.log('test');

When I make a request to get_data.js, the output I want is: test

当我向get_data.js发出请求时,我想要的输出是:test

But instead I get the source code:

但相反,我得到了源代码:

var fs = require('fs');

console.log('test');

Many thanks

2 个解决方案

#1


5

You're just asking for a static .js file, you're not interacting with Node at all. If you want to do so, make an HTTP server (copy the example on http://nodejs.org/), bind it to a port and write a response back, don't use console.log (which will only output to the console).

你只是要求一个静态的.js文件,你根本就没有与Node交互。如果你想这样做,建立一个HTTP服务器(复制http://nodejs.org/上的例子),将它绑定到一个端口并写回一个响应,不要使用console.log(它只会输出到控制台)。

Example:

Save the following file as app.js and then run it in the terminal with node app.js then visit localhost on port 1337:

将以下文件保存为app.js,然后在节点app.js的终端中运行它,然后访问端口1337上的localhost:

var http = require('http'),
    ajaxResponse = { 'hello': 'world' },
    htmlContent;

htmlContent  = "<html><title></title><head>";
htmlContent += "<script src='http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js'></script>";
htmlContent += "<script>$(function() {$.ajax({url:'/ajax',success:function(data){alert('success!');console.log(data);},error:function(data){alert('error!');}});});</script>";
htmlContent += "</head><body><h1>Hey there</h1>";
htmlContent +="</body></html>";

http.createServer(function (req, res) {   
  if (req.url === '/ajax') {
    res.writeHead(200, {'Content-Type': 'text/json'});
    res.end(JSON.stringify(ajaxResponse));
  } else {
    res.writeHead(200, {'Content-Type': 'text/html'});
    res.end(htmlContent);  
  }  
}).listen(1337, '127.0.0.1');
console.log('Server running at http://127.0.0.1:1337/');

更多相关文章

  1. Server.Htmlencode用于文本域显示带的html代码
  2. IOS学习之WebView加载本地HTML代码或网络资源
  3. html5 css3 背景视频循环播放代码
  4. HTML5 标签audio添加网页背景音乐代码
  5. 我无法理解为什么我的代码中的单击选择文本
  6. js字符串与html代码互相转换时怪想法:自己解析js字符串成普通字
  7. 解决FCKEditor编辑器在浏览器返回时显示html源代码的问题
  8. 高分求:如何解析IdHTTP获得的http代码?用mshttp的IHTMLDocument2可
  9. 韩顺平_轻松搞定网页设计(html+css+javascript)_第19讲_js运行原

随机推荐

  1. SQL根据某个字段分组查询:
  2. 特殊符号对应的ASCII码
  3. java.util.Date与java.sql.Date
  4. java之生成可重复执行的sql脚本
  5. Mysql-5.7 x64安装
  6. sqlite3使用教程1 SQLite 命令
  7. Linux系统下安装MySql 5.7.17 全过程
  8. SQL Sever数据库卡事务
  9. 查询自定义VO对象的sql
  10. 如果没有明确使用ISNULL,则左连接失败