使用JavaScript从URL中提取并使用JSON数据 [英] Pull and use JSON data from a URL with JavaScript
问题描述
如何使用JavaScript提取和使用JSON数据?
How can I pull and use JSON data using JavaScript?
例如,网址具有以下JSON:
For example, this URL has the following 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"
}
如何将这些数据转换为JavaScript变量?
How can I get this data into JavaScript variables?
我现在不打算使用Facebook API或任何动态,只是将静态URL中的JSON数据转换为JavaScript。
I'm not looking to use Facebook API or anything dynamic right now, just getting JSON data from a static URL into JavaScript.
在PHP中我可以很容易地这样做:
In PHP I could easily do this like:
$contents = file_get_contents($url);
$jsonObj = json_decode($contents);
echo "Name: ".$jsonObj->{'name'};
推荐答案
我推荐jQuery的 $。 getJSON()
方法
I recommend jQuery's $.getJSON()
method
http://api.jquery.com/jQuery.getJSON/
现场演示您的数据: http://jsfiddle.net/6ZeJ8/3/
当然,你需要jQuery来使用这个方法,把它放到你的HTML的< head>
中,应该可以正常工作。
Of course, you'll need jQuery to use this method, put this into the <head>
of your HTML, should work just fine.
<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.2.min.js"></script>
这篇关于使用JavaScript从URL中提取并使用JSON数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!