问题:
我正在尝试跨域使用 JSON,但我发现的只是 JSON 解析器,我不需要它...
我读过可以使用 JSON 进行跨域请求,
但到目前为止,我所看到的只是使用 XMLHttpRequest 的实现...
- 这意味着您不能使用跨域请求,至少不能在 IE 8 之外...
我一直在 http://www.json.org/ ,但我发现的要么是解析器,要么是无用的。
到目前为止,我在谷歌上找到的最好的是
http://devpro.it/JSON/files/JSONRequest-js.html
但这相当困惑,不能跨域工作,也不能在域内工作——或者根本不能工作……
var the_object = {};
var http_request = new XMLHttpRequest();
http_request.open( "GET", url, true );
http_request.onreadystatechange = function () {
if ( http_request.readyState == 4 && http_request.status == 200 ) {
the_object = JSON.parse( http_request.responseText );
}
};
http_request.send(null);
最佳答案
你可以跨域做的是注入(inject)一个脚本,包括:
var s = document.createElement('script');
s.src = 'http://someotherdomain/getMeMyJs.aspx?parameter=value';
s.onload = someOptionalCallback;
s.type = 'text/javascript';
if(document.getElementsByTagName('head').length > 0)
document.getElementsByTagName('head')[0].appendChild(s);
现在,该请求返回的代码将立即执行。如果你想让它与你的代码交互,你可以确保它与函数调用中包含的所有数据一起返回:
jsonCallback({ object: json, whatever: value });
您可以使用它来构建 API,您可以在其中将回调函数的名称作为请求查询字符串参数传递。 Here's an example of such an API
关于javascript - 跨域JSON请求?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2055186/