javascript - 跨域JSON请求?

标签 javascript json xmlhttprequest

问题:

我正在尝试跨域使用 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/

相关文章:

javascript - 具有集成安全性的跨域 POST

python - Flask 中的 JSON 数据是字符串还是字典?

html - 每个页面刷新时新的 MySQL 查询

javascript - jQuery AJAX get请求无法正常工作且返回值无法在控制台显示

javascript - Opera 和 Firefox 之间带有 XML 命名空间的 jQuery 和 xhr.responseXML 的区别

javascript - React-Redux,onClick不启动 Action 功能(未定义)

javascript - 新遗迹和 react

javascript - 如何检测不支持 XHR2 上传进度的浏览器

javascript - JavaScript 代理的替代品

python - 将 URL 中的 JSON 数据解析到 MySQL