这是一个恼人的问题,我不认为只有 IE 有这个问题。基本上我有一个 Node.js 服务器,我从中进行跨域调用以获取一些 JSON 数据以供显示。
这需要是一个 JSONP 调用,我在 URL 中给出了一个回调。我不确定的是,该怎么做?
所以网站 (domainA.com) 有一个带有 JS 脚本的 HTML 页面(在 Firefox 3 中一切正常):
<script type="text/javascript">
var jsonName = 'ABC'
var url = 'http://domainB.com:8080/stream/aires/' //The JSON data to get
jQuery.getJSON(url+jsonName, function(json){
// parse the JSON data
var data = [], header, comment = /^#/, x;
jQuery.each(json.RESULT.ROWS,function(i,tweet){ ..... }
}
......
</script>
现在我的 Node.js 服务器非常简单(我使用的是 express):
var app = require('express').createServer();
var express = require('express');
app.listen(3000);
app.get('/stream/aires/:id', function(req, res){
request('http://'+options.host+':'+options.port+options.path, function (error, response, body) {
if (!error && response.statusCode == 200) {
console.log(body); // Print the google web page.
res.writeHead(200, {
'Content-Type': 'application/json',
'Cache-Control': 'no-cache',
'Connection': 'keep-alive',
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Credentials': 'true'
});
res.end(JSON.stringify(JSON.parse(body)));
}
})
});
我如何更改这两个,以便它们可以在 IE 中使用跨域 GET?我一直在互联网上搜索,似乎有一些不同的东西,比如 jQuery.support.cors = true;
不起作用。似乎还有很多冗长的解决方法。
对于这类事情,我找不到真正的“理想”设计模式。
鉴于我可以控制网页和跨域 Web 服务,我要发送什么是最好的更改以确保所有 IE 版本以及 FireFox、Opera、Chrome 等的兼容性?
干杯!
最佳答案
假设我们有两个服务器,myServer.com 和 crossDomainServer.com,这两个服务器都是我们控制的。
假设我们希望 myServer.com 的客户端从 crossDomainServer.com 提取一些数据,首先该客户端需要向 crossDomainServer.com 发出 JSONP 请求:
// client-side JS from myServer.com
// script tag gets around cross-domain security issues
var script = document.createElement('script');
script.src = 'http://crossDomainServer.com/getJSONPResponse';
document.body.appendChild(script); // triggers a GET request
在跨域服务器上我们需要处理这个GET请求:
// in the express app for crossDomainServer.com
app.get('/getJSONPResponse', function(req, res) {
res.writeHead(200, {'Content-Type': 'application/javascript'});
res.end("__parseJSONPResponse(" + JSON.stringify('some data') + ");");
});
然后在我们的客户端 JS 中,我们需要一个全局函数来解析 JSONP 响应:
// gets called when cross-domain server responds
function __parseJSONPResponse(data) {
// now you have access to your data
}
适用于各种浏览器,包括 IE 6。
关于javascript - 来自 Node.JS(使用 express)服务器的跨域 jQuery.getJSON 在 Internet Explorer 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7596885/