[英]How to integrate ajax in Node.js?
我已經用Node.js概念測試了Hello world程序,並且運行良好。
文件詳細信息:
index.html
socket.js
在命令提示符下運行:node socket.js
我已經使用相同的hello world文件嘗試了node.js中的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
然后像這樣在瀏覽器中運行
然后,它提供以下輸出
_testcb('{“ message”:“你好,世界!”}')
但是我無法獲得正確的結果,請向我解釋一下,如何將Ajax與示例代碼集成到node.js中?
謝謝你的幫助。
更改您的writeHead函數以輸出JSON而不是純文本:
res.writeHead(200, {'Content-Type': 'application/json'});
請注意,jQuery不贊成使用success
和error
。 使用.then
和類似的承諾/延遲執行相關的方法來代替。
另外,請使用express
NPM庫而不是普通的node.js Web服務器-它為您完成了服務器上發送和接收JSON的大部分工作。
我試圖在nodeJS中實現簡單的AJAX,這是鏈接: nodesamples
希望能幫助到你 :)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.