Nig*_*olf 4 javascript jquery internet-explorer cross-domain node.js
这是一个烦人的问题,我不认为只有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>
Run Code Online (Sandbox Code Playgroud)
现在我的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)));
}
})
});
Run Code Online (Sandbox Code Playgroud)
如何更改这两个以便它们可以在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
Run Code Online (Sandbox Code Playgroud)
在跨域服务器上,我们需要处理此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') + ");");
});
Run Code Online (Sandbox Code Playgroud)
然后在我们的客户端JS中,我们需要一个全局函数来解析JSONP响应:
// gets called when cross-domain server responds
function __parseJSONPResponse(data) {
// now you have access to your data
}
Run Code Online (Sandbox Code Playgroud)
适用于各种浏览器,包括IE 6.
| 归档时间: |
|
| 查看次数: |
8560 次 |
| 最近记录: |