問題描述
問題:
我正在嘗試跨域使用 JSON,但我發現的只是 JSON 解析器,我不需要...
我讀過可以使用 JSON 進行跨域請求,但到目前為止,我看到的只是使用 XMLHttpRequest 的實現...
- 這意味著您不能使用跨域請求,至少不能在 IE 8 之外使用......
我一直在 http://www.json.org/,但我發現的只是解析器還是沒用.
到目前為止,我在谷歌上找到的最好的是
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 請求?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!