假设您的 JSON 结果是这样的:
{
"playlist": {
"track": {
"song": "Wake me up",
"albumart": "http://example.com/image.png",
"videoid": "CDsKBof4iMA"
},
"track": {
"song": "Wake me up 2",
"albumart": "http://example.com/image2.png",
"videoid": "CDsKBof4iMA2"
},
"track": {
"song": "Wake me up 3",
"albumart": "http://example.com/image3.png",
"videoid": "CDsKBof4iMA3"
}
}
}
更新:
此 json 格式无效,因为它有多个具有相同属性名称的子对象。如果可以,请将服务器的响应更改为以下格式:
{
playlist: {
tracks: [{
"song": "Wake me up",
"albumart": "http://example.com/image.png",
"videoid": "CDsKBof4iMA"
}, {
"song": "Wake me up 2",
"albumart": "http://example.com/image2.png",
"videoid": "CDsKBof4iMA2"
}, {
"song": "Wake me up 3",
"albumart": "http://example.com/image3.png",
"videoid": "CDsKBof4iMA3"
}]
}
}
然后您将能够track
从传递的数组中获取每个对象:
你应该$.getJSON
像这样使用你的功能:
$.getJSON("api/playlist/get.php", function (data) {
for (var key in myObj.playlist.tracks) {
//do something with your track object
console.log(myObj.playlist.tracks[key].song)
}
})
这是给你的 JsFiddle:http: //jsfiddle.net/zur4ik/Fy6ud/1/