最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Pull and use JSON data from a URL with JavaScript - Stack Overflow

programmeradmin4浏览0评论

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": "",
   "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'};

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./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'};
Share Improve this question edited Sep 27, 2016 at 13:34 fragilewindows 1,4121 gold badge16 silver badges26 bronze badges asked Apr 27, 2012 at 14:35 SmernSmern 19.1k22 gold badges76 silver badges93 bronze badges 0
Add a ment  | 

2 Answers 2

Reset to default 1

I remend jQuery's $.getJSON() method

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

Live demo with your data here: http://jsfiddle/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./jquery-1.7.2.min.js"></script>

You would need to use AJAX or a script loader to fetch your JSON string, then parse the JSON string.

发布评论

评论列表(0)

  1. 暂无评论