使用jquery的$ .ajax来获取node.js脚本的输出,而不是它的代码 [英] Use jquery's $.ajax to get a node.js script's output, not its code

查看:52
本文介绍了使用jquery的$ .ajax来获取node.js脚本的输出,而不是它的代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

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.

我做错了什么?

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

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

但我获得了源代码:

var fs = require('fs');

console.log('test');

非常感谢

推荐答案

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

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).

示例:

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

Save the following file as app.js and then run it in the terminal with node app.js then visit localhost on port 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/');

这篇关于使用jquery的$ .ajax来获取node.js脚本的输出,而不是它的代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆