跨域JSON请求? [英] Cross-domain JSON request?

查看:125
本文介绍了跨域JSON请求?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问题:

我正在尝试使用域中的JSON,但我找到的只是JSON解析器,我不需要...


我读过可以使用JSON,
进行跨域请求,但到目前为止,我看到的只是使用XMLHttpRequest的实现...

- 这意味着你不能使用跨域请求,至少不能在IE 8之外...


我一直在 http://www.json.org/ ,但我找到的只是解析器或没用。



到目前为止,我发现Google最好的是

http://devpro.it/JSON/files/JSONRequest-js.html


但这是一个混乱,不能跨域工作,并且内部 - 既不是 - 或者根本不是......

I'm trying to use JSON accross domains, but all i find is JSON parsers, which I don't need...
I've read that it's possible to do cross-domain requests with JSON, but so far, all I see is implementations that use XMLHttpRequest...
- which means you can't use cross-domain requests, at least not outside IE 8...
I've been on http://www.json.org/, but all I find is either parsers or useless.

The best I've found with google so far is
http://devpro.it/JSON/files/JSONRequest-js.html
but this is rather a mess, doesn't work cross domain, and intra-domain neither - or rather not at all...

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);


推荐答案

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

What you can do cross-domain is inject a script include:

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);

现在,该请求返回的代码将立即执行。如果你想让它与你的代码进行交互,你可以确保它被包含在函数调用中的所有数据返回:

Now, the code returned by that request will be executed immediately. If you want for that to interact with your code, you can make sure that it's being returned with all data wrapped in a function call:

jsonCallback({ object: json, whatever: value });

您可以使用它来构建API,您可以将回调函数的名称作为请求查询字符串传递参数。 以下是此类API的示例

You can use that to build APIs, where you pass the name of a callback function as a request querystring parameter. Here's an example of such an API

这篇关于跨域JSON请求?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆