简体   繁体   English

如何将Ajax集成到Node.js中?

[英]How to integrate ajax in Node.js?

I have tested the Hello world program with Node.js concept and it is working fine. 我已经用Node.js概念测试了Hello world程序,并且运行良好。

File details: 文件详细信息:

index.html index.html
socket.js socket.js

run in command prompt : node socket.js 在命令提示符下运行:node socket.js

And i have tried the ajax call in node.js using same hello world files and follow the code in the following link, 我已经使用相同的hello world文件尝试了node.js中的ajax调用,并按照以下链接中的代码进行操作,

how to use jQuery ajax calls with node.js 如何在node.js中使用jQuery ajax调用

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

And i run with the following method in the command prompt 我在命令提示符下使用以下方法运行

node node.js 节点node.js

And run in the browser like, 然后像这样在浏览器中运行

http://localhost:8080 http://本地主机:8080

Then, It provides the following output 然后,它提供以下输出

_testcb('{"message": "Hello world!"}') _testcb('{“ message”:“你好,世界!”}')

But i cant get the proper result, Please explain me, how to integrate the ajax in node.js with sample code? 但是我无法获得正确的结果,请向我解释一下,如何将Ajax与示例代码集成到node.js中?

Thanks for your help. 谢谢你的帮助。

更改您的writeHead函数以输出JSON而不是纯文本:

res.writeHead(200, {'Content-Type': 'application/json'});

Note that success and error are deprecated in jQuery. 请注意,jQuery不赞成使用successerror Use .then and similar promise/defered-related methods instead. 使用.then和类似的承诺/延迟执行相关的方法来代替。

Also, use express NPM library instead of plain node.js web server - it does most of this work on sending and receiving JSON on server for you. 另外,请使用express NPM库而不是普通的node.js Web服务器-它为您完成了服务器上发送和接收JSON的大部分工作。

I have tried to implement simple AJAX in nodeJS and this is the link: nodesamples 我试图在nodeJS中实现简单的AJAX,这是链接: nodesamples

Hope it helps :) 希望能帮助到你 :)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM