您好我试图像这样循环浏览一个json文件:
$.each(data.playlists.playlist, function(i, item) {
$("#contentC").append('<p>' + item.id + '</p>');
$("#contentC").append('<p>' + item.title + '</p>');
$("#contentC").append('<p>' + item.url + '</p>'); }
);
JSON:
{
"playlists":{
"playlist":[
{
"id":"8391802",
"title":"Second Playlist",
"description":"",
"date":"2011-03-06T18:53:33",
"size":"10",
"duration":"2267",
"streamable":"0",
"creator":"http:\/\/www.last.fm\/user\/jon21021985",
"url":"http:\/\/www.last.fm\/user\/jon21021985\/library\/playlists\/4zv5m_second_playlist",
"image":[
{
"#text":"",
"size":"small"
},
{
"#text":"",
"size":"medium"
},
{
"#text":"",
"size":"large"
},
{
"#text":"",
"size":"extralarge"
}
]
},
{
"id":"8372409",
"title":"All-american Rejects",
"description":"",
"date":"2011-02-28T13:30:01",
"size":"6",
"duration":"785",
"streamable":"0",
"creator":"http:\/\/www.last.fm\/user\/jon21021985",
"url":"http:\/\/www.last.fm\/user\/jon21021985\/library\/playlists\/4zg6x_all-american_rejects",
"image":[
{
"#text":"",
"size":"small"
},
{
"#text":"",
"size":"medium"
},
{
"#text":"",
"size":"large"
},
{
"#text":"",
"size":"extralarge"
}
]
}
],
"@attr":{
"user":"jon21021985"
}
}
}
问题是如果只有一个播放列表,则数据会发生变化,然后我会'未定义'
{
"playlists":{
"playlist":{
"id":"1319510",
"title":"Untitled",
"description":"",
"date":"2007-10-18T12:17:58",
"size":"1",
"duration":"345",
"streamable":"0",
"creator":"http:\/\/www.last.fm\/user\/john",
"url":"http:\/\/www.last.fm\/user\/john\/library\/playlists\/sa52_",
"image":[
{
"#text":"",
"size":"small"
},
{
"#text":"",
"size":"medium"
},
{
"#text":"",
"size":"large"
},
{
"#text":"",
"size":"extralarge"
}
]
},
"@attr":{
"user":"john"
}
}
}
答案 0 :(得分:11)
if($.isArray(data.playlists.playlist))
{
$.each(data.playlists.playlist, function(i, item) {
displayPlayList(item)
);
}
else
{
displayPlayList(data.playlists.playlist);
}
//this way of appending an element is very poor coding practice but
//i have done this way, because u yourself have written this
// if u want then i can suggest you, how can u optimize this code
function displayPlayList(item)
{
$("#contentC").append('<p>' + item.id + '</p>');
$("#contentC").append('<p>' + item.title + '</p>');
$("#contentC").append('<p>' + item.url + '</p>'); }
}
修改强>
正如Emmet指出的那样,你应该总是返回数组。但是在你使用派对json服务并且他们以这种格式返回数据的情况下它是可以接受的,那么你无能为力