无法让getJSON显示数组中的值
我在显示$.getJSON
调用的内容时遇到问题。 我有这个代码从页面中检索一些JSON数据。
var loadItems = function() { if (hasNextPage === false) { return false } pageNum = pageNum + 1; var url = baseUrl + "json/" + pageNum + '/'; var jqxhr = $.getJSON(url, function (data) { var a = []; $.each(data.itemList, function (item) { a.push("" + item.title + " "); }); $("
", {html: a.join(" ")}).appendTo("#anchor"); }); jqxhr.complete(function () { alert('done!'); $(window).bind('scroll', loadOnScroll); }); };
这个想法只是根据滚动位置动态加载页面,并获取该页面的JSON内容(用于无限滚动效果)。 JSON结构是这样的:
{ "key1": val1, "key2": val2, "itemList": [ {"title": "title", "author": "author", "id": 100, "slug": slug, }, ... ] }
重要的值在itemList中,我必须检索将插入到我的django模板中的数据,然后该模板将从视图中获取一些数据。 除了我无法访问itemList中的数据外,一切似乎都运行得很好。 似乎没有任何东西被推入arrays。 因为页面上没有显示任何内容(即应该创建的
编辑:
我做了一些bug跟踪,发现代码永远不会执行$ .each循环。 不知道如何解决这个问题。
你应该使用错误日志来检查出错的地方:并且始终在$.each
使用index,obj格式是安全的。
$.getJSON(url).success( function( data ) { console.log(data); $.each(data.itemList, function (index, item) { a.push("" + item.title + " "); }); $("
", {html: a.join(" ")}).appendTo("#anchor"); }).error(function(error){ console.log(error);// see if you are getting in error log.. });
你的json数据也错了它应该是这样的:
{ "key1": "val1", "key2": "val2", "itemList": [ { "title": "title", "author": "author", "id": 100, "slug": "slug" },....... ] }
尝试使用更正的数据,它将起作用。 你可以在这里查看你的数据: http : //json.parser.online.fr/
您在使用时看到了代码中的问题
$.each() //It should using for dictionary.
所以我有两个解决方案给你
1)您可以使用forEach方法。
例如:
`if(data != null && data.itemList.length > 0) { data.itemList.forEach(function (item) { a.push("" + item.title + " "); }); }`
==>这种方式适用于IE 10+和其他浏览器。
2)使用$ .each方法
例如:
if(data != null && data.itemList.length > 0) { $.each(data.itemList, function (key, item) { a.push("" + item.title + " "); }); }
==>您的Json数据是字典类型,因此如果您使用$ .each,则需要定义两个变量
key: is the key of data. item: is the value of data.
注意:这种方式适用于所有浏览器版本。
希望这可以帮助你。
这是因为你的’item’是一个索引,而不是你想要的’对象’。 你必须使用第二个参数:
$.each(data.itemList, function (index, item) { a.push("" + item.title + " "); });
还有, hasNextPage
定义在哪里? 是定义了吗? 你也可以缩短到:
if (!hasNextPage) return;