[英]how to use jQuery ajax calls with node.js
這類似於使用Node.js的Stream數據 ,但是我覺得這個問題沒有得到足夠的回答。
我正在嘗試使用jQuery ajax調用(get,load,getJSON)在頁面和node.js服務器之間傳輸數據。 我可以從瀏覽器中找到該地址,然后看到“ Hello World!”,但是當我從頁面嘗試此操作時,它失敗並顯示我沒有回信。我設置了一個簡單的測試頁面和hello world示例進行測試:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>get test</title>
</head>
<body>
<h1>Get Test</h1>
<div id="test"></div>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.js"></script>
<script>
$(document).ready(function() {
//alert($('h1').length);
$('#test').load('http://192.168.1.103:8124/');
//$.get('http://192.168.1.103:8124/', function(data) {
// alert(data);
//});
});
</script>
</body>
</html>
和
var http = require('http');
http.createServer(function (req, res) {
console.log('request received');
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello World\n');
}).listen(8124);
如果您的簡單測試頁位於hello world node.js示例之外的其他協議/域/端口上,則說明您正在執行跨域請求並且違反了相同的原始策略,因此jQuery ajax調用(獲取和加載)會靜默失敗。 為了獲得跨域工作的效果,您應該使用基於JSONP的格式。 例如node.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(8124);
和客戶端JavaScript / jQuery:
$(document).ready(function() {
$.ajax({
url: 'http://192.168.1.103:8124/',
dataType: "jsonp",
jsonpCallback: "_testcb",
cache: false,
timeout: 5000,
success: function(data) {
$("#test").append(data);
},
error: function(jqXHR, textStatus, errorThrown) {
alert('error ' + textStatus + " " + errorThrown);
}
});
});
感謝yojimbo的回答。 要添加到他的示例中,我想使用jquery方法$ .getJSON,該方法在查詢字符串中放置了一個隨機回調,因此我也想在Node.js中進行解析。 我還想將一個對象傳遞回並使用stringify函數。
這是我的客戶端代碼。
$.getJSON("http://localhost:8124/dummy?action=dostuff&callback=?",
function(data){
alert(data);
},
function(jqXHR, textStatus, errorThrown) {
alert('error ' + textStatus + " " + errorThrown);
});
這是我的服務器端Node.js
var http = require('http');
var querystring = require('querystring');
var url = require('url');
http.createServer(function (req, res) {
//grab the callback from the query string
var pquery = querystring.parse(url.parse(req.url).query);
var callback = (pquery.callback ? pquery.callback : '');
//we probably want to send an object back in response to the request
var returnObject = {message: "Hello World!"};
var returnObjectString = JSON.stringify(returnObject);
//push back the response including the callback shenanigans
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end(callback + '(\'' + returnObjectString + '\')');
}).listen(8124);
我想您的HTML頁面托管在其他端口上。 同源策略, 需要在加載文件是相同的端口而不是加載文件大多數瀏覽器上。
在服務器端使用類似以下的內容:
http.createServer(function (request, response) {
if (request.headers['x-requested-with'] == 'XMLHttpRequest') {
// handle async request
var u = url.parse(request.url, true); //not needed
response.writeHead(200, {'content-type':'text/json'})
response.end(JSON.stringify(some_array.slice(1, 10))) //send elements 1 to 10
} else {
// handle sync request (by server index.html)
if (request.url == '/') {
response.writeHead(200, {'content-type': 'text/html'})
util.pump(fs.createReadStream('index.html'), response)
}
else
{
// 404 error
}
}
}).listen(31337)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.