getJSON数据变量

时间:2015-11-15 11:42:46

标签: javascript jquery json

我试图通过$ .getJSON从JSON获取数据并将其分配给变量,所以稍后我可以迭代它。 截至目前,我的代码看起来像这样:

var myJson;

$.getJSON("http://www.json-generator.com/api/json/get/ceQSpTWJTS?indent=2", function(json){
  if (json != null){
    console.log("Load successfull");
  };        
  myJson = json;
});

var main = document.getElementsByClassName("main");
var sec = document.getElementsByClassName("sec");
var entries = myJson.friends;

function myF_1(){
  for(var i = 0; i < items.length; i++) {    
    main[i].innerHTML = entries[i].id;              
  }
};

function myF_2(){
  for(var i = 0; i < items.length; i++) {    
    sec[i].innerHTML = entries[i].name;
  }
};

main.innerHTML = myF_1();
sec.innerHTML = myF_2();

虽然我从var main = document.getElementsByClassName("main");开始大多是肯定的,但代码是正确的(之前有效)。 问题是,即使$.getJSON部分似乎也没问题。控制台正在返回Load Successfull,就像它应该的那样。 我得到的错误如下:Uncaught TypeError: Cannot read property 'friends' of undefined,所以它显然与我的JSON有关。我的JSON看起来像这样:

[
  {
    "_id": "56486b9a3fa6be06a434586a",
    "index": 0,
    "guid": "0ae0d91a-f06e-4657-93a2-b36cdce9539c",
    "isActive": true,
    "balance": "$2,013.92",
    "picture": "http://placehold.it/32x32",
    "age": 35,
    "eyeColor": "blue",
    "name": "Gladys Davis",
    "gender": "female",
    "company": "ZOINAGE",
    "email": "gladysdavis@zoinage.com",
    "phone": "+1 (980) 578-2162",
    "address": "942 Sandford Street, Bannock, Wyoming, 7863",
    "about": "Sit laboris est ut est duis aute occaecat do aliqua do elit in culpa. Elit deserunt anim consequat adipisicing sint. Id sit ullamco exercitation dolore ex fugiat minim Lorem sint voluptate.\r\n",
    "registered": "2014-07-18T01:02:49 -02:00",
    "latitude": -39.674779,
    "longitude": 91.675051,
    "tags": [
    "deserunt",
    "ex",
    "sunt",
    "ipsum",
    "sint",
    "culpa",
    "consectetur"
    ],
"friends": [
  {
    "id": 0,
    "name": "Casandra Walter"
  },
  {
    "id": 1,
    "name": "Wolf Medina"
  },
  {
    "id": 2,
    "name": "Florine Osborne"
  }
],
"greeting": "Hello, Gladys Davis! You have 5 unread messages.",
"favoriteFruit": "strawberry"
},

我不知道该怎么做。为什么friends未定义?

0 个答案:

没有答案