我得到这个代码来获取一个json对象,这是有效的。
$.getJSON("http://api.songkick.com/api/3.0/artists/" + artist_id + "/calendar.json?apikey=Key&jsoncallback=?", function callback(json) {
$.each(json["resultsPage"], function (i, entry) {
alert(entry.totalEntries);
});
});
当我执行代码时,如果没有关于艺术家的数据,我会得到这个:
?({"resultsPage":{"results":{},"totalEntries":0,"perPage":50,"page":1,"status":"ok"}})
我想要的是获取totalEntries的值来验证是否有一些数据,但我一直得到UNDEFINED。我正在使用警报来显示价值。
可能是什么问题,或者更好的方法来获取totalEntries或验证查询是否有异议。
一个好的(当找到某事时):
{"resultsPage":{"results":{"artist":[{"uri":"http:\/\/www.songkick.com\/artists\/462022-britney-spears?utm_source=11548&utm_medium=partner","displayName":"Britney Spears","id":462022,"onTourUntil":null,"identifier":[{"href":"http:\/\/api.songkick.com\/api\/3.0\/artists\/mbid:45a663b5-b1cb-4a91-bff6-2bef7bbfdd76.json","eventsHref":"http:\/\/api.songkick.com\/api\/3.0\/artists\/mbid:45a663b5-b1cb-4a91-bff6-2bef7bbfdd76\/calendar.json","mbid":"45a663b5-b1cb-4a91-bff6-2bef7bbfdd76","setlistsHref":"http:\/\/api.songkick.com\/api\/3.0\/artists\/mbid:45a663b5-b1cb-4a91-bff6-2bef7bbfdd76\/setlists.json"}]},{"uri":"http:\/\/www.songkick.com\/artists\/5034848-hits-of-pink-christina-aguilera-britney-spears-and-motley-crue?utm_source=11548&utm_medium=partner","displayName":"Hits of Pink, Christina Aguilera, Britney Spears and M\u00f6tley Cr\u00fce","id":5034848,"onTourUntil":null,"identifier":[]},{"uri":"http:\/\/www.songkick.com\/artists\/2885106-kimberly-dale-as-britney-spears?utm_source=11548&utm_medium=partner","displayName":"Kimberly Dale As Britney Spears","id":2885106,"onTourUntil":null,"identifier":[]}]},"totalEntries":3,"perPage":50,"page":1,"status":"ok"}}
答案 0 :(得分:0)
您正在迭代“resultsPage”的字段,而不是“resultsPage”本身。我想你的意思是:
alert(json.resultsPage.totalEntries); // Without the "each", you don't need it
自己测试,将代码更改为
$.each(json["resultsPage"], function (i, entry) {
alert([i, entry]);
});
它会发出警报(没有特别的顺序):
results, [object Object]
totalEntries, 0
perPage, 50
page, 1
status, ok