使用jquery';s$.ajax获取node.js脚本';s的输出,而不是它的代码

使用jquery';s$.ajax获取node.js脚本';s的输出,而不是它的代码,ajax,node.js,jquery,Ajax,Node.js,Jquery,我正在构建一个小型原型,存在以下问题: 我正在尝试在客户端jQuery和服务器端node.js之间进行通信;当我向node.js代码发出jQuery ajax请求时,它只给出代码,而不是代码的输出 我做错了什么 client.js的一部分: $.ajax({url : './../includes/get_data.js', success : function(data) { alert('success!'); },

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

我正在尝试在客户端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!');
        }
});  
var fs = require('fs');

console.log('test');
get_data.js:

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

console.log('test');
当我请求获取_data.js时,我想要的输出是: 试验

但我得到的是源代码:

var fs = require('fs');

console.log('test');

非常感谢

您只需要一个静态的.js文件,根本不需要与节点交互。如果要这样做,请创建一个HTTP服务器(复制上的示例),将其绑定到一个端口并写回响应,不要使用console.log(它将只输出到控制台)

例如:

将以下文件另存为app.js,然后在带有
节点app.js
的终端中运行它,然后访问端口1337上的本地主机:

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/');
var http=require('http'),
ajaxResponse={'hello':'world'},
htmlContent;
htmlContent=“”;
htmlContent+=“”;
htmlContent+=“$(function(){$.ajax({url:'/ajax',成功:函数(数据){alert('success!');console.log(数据);},错误:函数(数据){alert('error!');}});”;
htmlContent+=“你好”;
htmlContent+=“”;
http.createServer(函数(req,res){
如果(req.url=='/ajax'){
res.writeHead(200,{'Content-Type':'text/json'});
res.end(JSON.stringify(ajaxResponse));
}否则{
res.writeHead(200,{'Content-Type':'text/html'});
res.end(htmlContent);
}  
}).听(1337,'127.0.0.1');
console.log('服务器在运行http://127.0.0.1:1337/');

我猜您希望在服务器(运行节点)上获取某个URL,然后在服务器上执行GET_data.js中的代码

如果是这样,请使用express-查看

  • 在Node Express的app.get()中。。。
  • 第一个参数-提供所需的路由(例如,'/mygetdata')
  • 第二个参数-在这个回调函数中,调用get_data.js代码
  • 在客户端代码中,修改它以请求URL(例如,''),而不是get_data.js

您的服务器端node.js环境是如何设置的?据我所见,您试图以CGI脚本的形式访问它,而node.js通常不是这样使用的。嗯。。。现在就检查这个。我可能只需要让我的服务器执行代码,然后将其发送回:P。谢谢您的解释。检查你的答案。