使用jquery的$ .ajax来获取node.js脚本的输出,而不是它的代码
我正在构建一个小型原型,并存在以下问题:
我试图在客户端jQuery和服务器端node.js之间进行通信; 当我向我的node.js代码发出jQuery ajax请求时,它只是给我代码,而不是代码的输出。
我究竟做错了什么?
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');
当我向get_data.js发出请求时,我想要的输出是:test
但相反,我得到了源代码:
var fs = require('fs'); console.log('test');
非常感谢
你只是要求一个静态的.js文件,你根本就没有与Node交互。 如果你想这样做,建立一个HTTP服务器(复制http://nodejs.org/上的例子),将它绑定到一个端口并写回一个响应,不要使用console.log(它只会输出到控制台)。
例:
将以下文件保存为app.js,然后在node app.js
的终端中运行它,然后访问端口1337上的localhost:
var http = require('http'), ajaxResponse = { 'hello': 'world' }, htmlContent; htmlContent = " "; htmlContent += ""; htmlContent += ""; htmlContent += "Hey there
"; htmlContent +=""; 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/');
我猜你想要在服务器上运行某个URL(运行Node),然后执行服务器上get_data.js中的代码?
如果是这样,请使用express – 查看http://expressjs.com/api.html#express 。
- 在Node Express的app.get()中……
- 第一个arg – 提供你想要的路线(例如’/ mygetdata’)。
- 第二个arg – 在此回调函数中,调用get_data.js代码
- 在您的客户端代码中,修改它以请求URL(例如,“ http://mywebsite.com/mygetdata ”),而不是get_data.js。