跨域JSON请求?

Ste*_*ger 14 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);
Run Code Online (Sandbox Code Playgroud)

Dav*_*und 14

你可以做的跨域注入脚本包括:

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);
Run Code Online (Sandbox Code Playgroud)

现在,该请求返回的代码将立即执行.如果您希望与代码进行交互,则可以确保返回包含在函数调用中的所有数据:

jsonCallback({ object: json, whatever: value });
Run Code Online (Sandbox Code Playgroud)

您可以使用它来构建API,您可以将回调函数的名称作为请求查询字符串参数传递.这是一个这样的API的例子

  • 这通常称为JSONP(带填充的JSON).见http://en.wikipedia.org/wiki/JSONP#JSONP (5认同)

Ofr*_*viv 13

JSON只是一种序列化方法.序列化方法与浏览器是否会试图阻止您跨域访问数据之间没有任何关系.(这解释了为什么你只找到解析器 - JSON没有任何东西,除了编码和解码它).

XMLHTTPRequest名为XML HTTPRequest.它与XML没有任何关系.它可用于发送文本数据,以JSON编码的数据或任何其他序列化方法.

有几种方法可以访问数据跨域.在David Hedlund的回答中描述了一个.其他人可以找到类似问题的答案(见这里这里).