循环 JSON 时无法读取未定义的属性 0。
2014-02-24
2067
我正在使用 jQuery ajax 方法检索 JSON 中的一些信息,并收到以下错误。
Uncaught TypeError: Cannot read property '0' of undefined
fullName 已成功输出一次。 是什么导致了此错误?
JSON
{
"sports":[
{
"name":"soccer",
"id":600,
"uid":"s:600",
"leagues":[
{
"name":"Barclays Premier League",
"abbreviation":"eng.1",
"id":700,
"isTournament":false,
"country":{
"id":31,
"name":"England",
"abbreviation":"ENG"
},
"uid":"s:600~l:700",
"groupId":23,
"shortName":"Premier League",
"athletes":[
{
"id":108350,
"firstName":"Charlie",
"lastName":"Adam",
"fullName":"Charlie Adam",
"displayName":"Charlie Adam",
"shortName":"C. Adam",
"links":{
"api":{
"athletes":{
"href":"http://api.espn.com/v1/sports/soccer/eng.1/athletes/108350"
},
"news":{
"href":"http://api.espn.com/v1/sports/soccer/eng.1/athletes/108350/news"
},
"notes":{
"href":"http://api.espn.com/v1/sports/soccer/eng.1/athletes/108350/news/notes"
}
},
"web":{
"athletes":{
"href":"http://espnfc.com/player/_/id/108350?ex_cid=espnapi_public"
}
},
"mobile":{
"athletes":{
"href":"http://m.espn.go.com/soccer/profile?id=108350&ex_cid=espnapi_public"
}
}
}
},
{
"id":16684,
"firstName":"Emmanuel",
"lastName":"Adebayor",
"fullName":"Emmanuel Adebayor",
"displayName":"Emmanuel Adebayor",
"shortName":"E. Adebayor",
"links":{
"api":{
"athletes":{
"href":"http://api.espn.com/v1/sports/soccer/eng.1/athletes/16684"
},
"news":{
"href":"http://api.espn.com/v1/sports/soccer/eng.1/athletes/16684/news"
},
"notes":{
"href":"http://api.espn.com/v1/sports/soccer/eng.1/athletes/16684/news/notes"
}
},
"web":{
"athletes":{
"href":"http://espnfc.com/player/_/id/16684?ex_cid=espnapi_public"
}
},
"mobile":{
"athletes":{
"href":"http://m.espn.go.com/soccer/profile?id=16684&ex_cid=espnapi_public"
}
}
}
},
jQuery
$.ajax({
url: "http://api.espn.com/v1/sports/soccer/eng.1/athletes",
data: {
// enter your developer api key here
apikey: "hidden",
_accept: "application/json"
},
dataType: "jsonp",
success: function(data) {
console.log(data);
for (var i = 0; i < data.sports[0].leagues[0].athletes.length; i++) {
var data = data.sports[0].leagues[0].athletes[i].fullName;
$('body').append('<ul/>');
$('body').append('<li>' + data + '</li>');
}
},
error: function() {
console.log('error');
}
});
1个回答
您有两个问题。首先,您正在覆盖变量数据,因此出现未定义错误。第二个问题是您错误地附加了 ul 和 li。
success: function(data) {
var ul = $('<ul/>').appendTo("body"); //make a ul and append it to the body
var athletes = data.sports[0].leagues[0].athletes; //store a reference so code is faster and easier to read
for (var i = 0; i < athletes.length; i++) {
var name = athletes[i].fullName;
ul.append('<li>' + name + '</li>'); //add the li to the new ul you created.
}
},
epascarello
2014-02-24