简体   繁体   中英

Pull and use JSON data from a URL with JavaScript

How can I pull and use JSON data using JavaScript?

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"
}

How can I get this data into JavaScript variables?

I'm not looking to use Facebook API or anything dynamic right now, just getting JSON data from a static URL into JavaScript.

In PHP I could easily do this like:

$contents = file_get_contents($url);
$jsonObj = json_decode($contents);
echo "Name: ".$jsonObj->{'name'};

您需要使用AJAX脚本加载器来获取JSON字符串,然后解析 JSON字符串。

I recommend jQuery's $.getJSON() method

http://api.jquery.com/jQuery.getJSON/

Live demo with your data here: 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.

<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.2.min.js"></script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM