我用Node.js概念测试了Hello world程序,它工作正常 .
文件详情:
的index.html
socket.js
在命令提示符下运行:node socket.js
我已经尝试使用相同的hello world文件在node.js中调用ajax,并按照以下链接中的代码进行操作,
how to use jQuery ajax calls with node.js
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 node.js
并在浏览器中运行,
然后,它提供以下输出
_testcb('{“message”:“Hello world!”}')
但我无法得到正确的结果,请解释一下,如何将node.js中的ajax与示例代码集成?
谢谢你的帮助 .
3 回答
将writeHead函数更改为输出JSON而不是纯文本:
请注意,
success
和error
在jQuery中已弃用 . 请改用.then
和类似的promise / defered相关方法 .此外,使用
express
NPM库而不是普通的node.js Web服务器 - 它的大部分工作都是在服务器上为您发送和接收JSON .我试图在nodeJS中实现简单的AJAX,这是链接:nodesamples
希望能帮助到你 :)