如何在Node.js中集成ajax?
我已经用Node.js的概念testing了Hello world程序,它工作的很好。
档案细节:
的index.html
socket.js
在命令提示符下运行:节点socket.js
我已经尝试使用相同的hello世界文件在node.js中的ajax调用,并按照下面的链接中的代码,
如何与node.js一起使用jQuery ajax调用
server.js
var http = require('http'); http.createServer(function (req, res) { console.log('request received'); res.writeHead(200, {'Content-Type': 'text/plain'}); res.end('_testcb(\'{"message": "Hello world!"}\')'); }).listen(8080);
的index.html
<script src="/socket.io/socket.io.js"></script> <script> $(document).ready(function() { $.ajax({ url: 'http://localhost:8080/', dataType: "jsonp", jsonpCallback: "_testcb", cache: false, timeout: 5000, success: function(data) { $("#test").append(data); }, error: function(jqXHR, textStatus, errorThrown) { alert('error ' + textStatus + " " + errorThrown); } }); }); </script> <div id="test"></div>
而我在命令提示符下使用以下方法运行
节点node.js
并在浏览器中运行,
HTTP://本地主机:8080
然后,它提供以下输出
_testcb('{“message”:“Hello world!”}')
但我不能得到正确的结果,请解释我,如何在示例代码中集成ajax在node.js?
谢谢你的帮助。
改变你的writeHead函数输出JSON而不是纯文本:
res.writeHead(200, {'Content-Type': 'application/json'});
请注意, success
和error
在jQuery中被弃用。 然后使用和类似的promise / defered相关的方法。
此外,使用express
NPM库,而不是简单的node.jsnetworking服务器 – 它的大部分工作是在您的服务器上发送和接收JSON。
我试图在nodeJS中实现简单的AJAX,这是链接: nodesamples
希望能帮助到你 :)