javascript 从 URL 读取 JSON
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10586024/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Read JSON from URL
提问by wiseindy
I'm facing a problem which should be really simple to solve, but I am lost as of now.
我面临一个应该很容易解决的问题,但我现在迷路了。
I have a url: http://search.twitter.com/search.json?q=bacon
我有一个网址:http: //search.twitter.com/search.json?q= bacon
Using JavaScript (not JQuery or php. Just JavaScript), I want to read this JSON string and parse it. That's it.
使用 JavaScript(不是 JQuery 或 php。只是 JavaScript),我想读取这个 JSON 字符串并解析它。而已。
Thanks!
谢谢!
回答by Matt
You'll be restricted by the SOP(XMLHttpRequest
s can only be made to URI's on the same domain; JSON can only be retrieved via this method). To bypass this you'll have to use JSONP instead(other explanation*).
您将受到SOP 的限制(XMLHttpRequest
只能将 s 设置为同一域上的 URI;只能通过此方法检索 JSON)。要绕过这一点,您必须改用 JSONP(其他解释*)。
It seems the endpoint supports JSONP, so you can do:
端点似乎支持 JSONP,因此您可以执行以下操作:
function foo(response) {
// response is already a JavaScript object
}
var script = document.createElement("script");
script.src = "http://search.twitter.com/search.json?q=bacon&callback=foo";
document.body.appendChild(script);
* Disclaimer: Yep, thats my blog
* 免责声明:是的,那是我的博客