2011-07-12 148 views
0

我正在通过jQuery使用一些JSON,并认为我正确地做了这件事,但我一直未定义。JSON对象访问器返回undefined

如果我的JSON的组织,像这样:

{ "item1" : "answer", 
    "name" : "something", 
    "title" : "your title", 
    "favorites" : [ { 
     "color" : "blue", 
     "season" : "winter", 
     "sport" : "baseball" 
     }, 
     { ... more favorite objects ... }] 
} 

然后,我把它与

$.getJSON(urlOfMyJSON, null, function(json){ 
    $("p").append(json.item1); // returns 'answer' 
    $("h3").append(json.favorites); // returns undefined 
    $("h4").append(json.favorites[0].color); // thought this should work; throws an error because undefined has no "color". 
}); 

任何人都可以请点我在正确的方向?我知道我想要做什么,我只是不太确定我错过了什么。

谢谢!

+0

将json放入console.log中,看看会发生什么。 – cwallenpoole

+2

您的json引用没有出现任何问题,因此问题必须与您看到的实际JSON或与您的HTML相关的内容(您没有显示)。我也没有看到你可以用一串字符串调用append。 – jfriend00

回答

1

没有什么不对您的JSON或访问所产生的反序列化对象的属性代码。 Live example.但是,该行:

$("h3").append(json.favorites); 

没有多大意义。你问的jQuery借此数组:

[ 
    { 
     "color" : "blue", 
     "season" : "winter", 
     "sport" : "baseball" 
    } 
] 

...并将它添加到您的所有网页上h3元素。 jQuery将使用toString,因为它不是DOM元素或jQuery实例,并且toString可能会返回[object Object]或类似。

下一行,$("h4").append(json.favorites[0].color);,应该正常工作,正如上面的实时链接演示。只要网页上有h4个元素即可更新!

1

做到这一点,看问题:

$.getJSON(urlOfMyJSON, null, function(json){ 
    alert(json.toSource()); 
});