如何修改Request.JSON以满足跨域安全
我正在使用 mootools 从我的 Web 处理程序请求 json,并且在同一台机器上运行良好。我在一些地方读到过有关需要回调来满足跨域问题的信息,但不确定如何应用它。我想从另一个域运行此代码。
var 输入 = [];
var jsonRequest = new Request.JSON({
url: "http://www.mysite.com.au/GetImages.ashx?p=2",
onSuccess: function (result) {
for (var i = 0; i < result.length; i++) {
// alert(result[i].MediaPath);
var s = result[i].MediaPath.split('|');
for (var j = 0; j < s.length; j++) {
// alert(s[j]);
input.push(s[j]);
}
}
}
}).get();
干杯!
I'm using mootools to request json from my web handler and this is working fine from the same machine. I've read in places about need for a callback to satisfy cross domain issues but unsure how to apply this. I'd like to run this code from another domain.
var input = [];
var jsonRequest = new Request.JSON({
url: "http://www.mysite.com.au/GetImages.ashx?p=2",
onSuccess: function (result) {
for (var i = 0; i < result.length; i++) {
// alert(result[i].MediaPath);
var s = result[i].MediaPath.split('|');
for (var j = 0; j < s.length; j++) {
// alert(s[j]);
input.push(s[j]);
}
}
}
}).get();
cheers!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
一种解决方案是使用 JSONP。
这是您将使用的客户端代码:
这是服务器将响应的内容:
使此工作有效的技巧是服务器在技术上不再返回 json 数据。相反,它将返回由 javascript 函数(客户端代码将定义)包装的 json 数据,该函数将由浏览器自动执行,因为这就是浏览器对标签的处理方式。
如果您需要动态收集它,那么您可以让 javascript 代码创建一个 script 元素,将 url 添加为“src”属性,然后将 script 标记附加到 body 以使浏览器执行它。这个技巧是一种非常标准的动态下载脚本的方法。 MooTools可能已经有办法做到这一点。
我的建议的缺点是:它不再是异步的。
One solution is to use JSONP.
Here is the client-side code you would use:
Here is what the server would respond with:
The trick which makes this work is that the server no longer technically returns json data. Instead, it will return json data wrapped by a javascript function (which the client-side code will define) that will automatically be executed by the browser because that's what browsers do with tags.
If you need to have it dynamically gathered, then you can have javascript code create a script element, add the url as the 'src' attribute, then append the script tag to body to have the browser execute it. This hack is a very standard way to dynamically download scripts. MooTools might already have a way to do this.
Downside with my suggestion: it is no longer asynchronous.
另一个潜在的解决方案是让您的服务器代理来自其他站点的 json 请求。我不熟悉如何完成此操作,但我认为 SOAP 协议实现了这一点。
Another potential solution is to have your server proxy the json requests from other sites. I am unfamiliar with how this would be done, but I think that the SOAP protocol implements this.