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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 10:22:16  来源:igfitidea点击:

Read JSON from URL

javascriptajaxjsonurl

提问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(XMLHttpRequests 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

* 免责声明:是的,那是我的博客