bri*_*nad 70 html javascript ajax jquery 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>
Run Code Online (Sandbox Code Playgroud)
和
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);
Run Code Online (Sandbox Code Playgroud)
yoj*_*o87 86
如果您的简单测试页面位于其他协议/域/端口而不是您的hello world node.js示例,那么您正在执行跨域请求并违反相同的源策略,因此您的jQuery ajax调用(get和load)会无声地失败.要使这个跨域工作,您应该使用基于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);
Run Code Online (Sandbox Code Playgroud)
和客户端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);
}
});
});
Run Code Online (Sandbox Code Playgroud)
还有其他方法可以实现这一点,例如通过设置反向代理或完全使用像express这样的框架构建Web应用程序.
感谢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);
});
Run Code Online (Sandbox Code Playgroud)
这是我的服务器端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);
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
101238 次 |
最近记录: |