使用 JavaScript 从 URL 中提取和使用 JSON 数据
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10352636/
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
Pull and use JSON data from a URL with JavaScript
提问by Dallas
How can I pull and use JSON data using JavaScript?
如何使用 JavaScript 提取和使用 JSON 数据?
For example, this URLhas the following JSON:
例如,此URL具有以下 JSON:
{
"id": "220439",
"name": "Bret Taylor",
"first_name": "Bret",
"last_name": "Taylor",
"link": "http://www.facebook.com/btaylor",
"username": "btaylor",
"gender": "male",
"locale": "en_US"
}
How can I get this data into JavaScript variables?
如何将这些数据放入 JavaScript 变量中?
I'm not looking to use Facebook API or anything dynamic right now, just getting JSON data from a static URL into JavaScript.
我现在不打算使用 Facebook API 或任何动态的东西,只是将 JSON 数据从静态 URL 获取到 JavaScript 中。
In PHP I could easily do this like:
在 PHP 中,我可以很容易地做到这一点:
$contents = file_get_contents($url);
$jsonObj = json_decode($contents);
echo "Name: ".$jsonObj->{'name'};
回答by Joseph
回答by IsisCode
I recommend jQuery's $.getJSON()
method
我推荐jQuery的$.getJSON()
方法
http://api.jquery.com/jQuery.getJSON/
http://api.jquery.com/jQuery.getJSON/
Live demo with your data here: http://jsfiddle.net/6ZeJ8/3/
在此处使用您的数据进行现场演示:http: //jsfiddle.net/6ZeJ8/3/
Of course, you'll need jQuery to use this method, put this into the <head>
of your HTML, should work just fine.
当然,你需要 jQuery 来使用这个方法,把它放到<head>
你的 HTML 中,应该可以正常工作。
<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.2.min.js"></script>