[Answer]-Trouble getting getJSON to display values from array

1👍

you should be using error log to check what is going wrong:and always use index,obj format in $.each to be safe.

 $.getJSON(url).success( function( data ) {
                    console.log(data);
    $.each(data.itemList, function (index, item) {
    a.push("<li>" + item.title + "</li>");
   });
    $("<ul/>", {html: a.join(" ")}).appendTo("#anchor");

                }).error(function(error){
                    console.log(error);// see if you are getting in error log..
                });

and your json data is also wrong it should be something like this:

{ "key1": "val1",
 "key2": "val2",
 "itemList": 
[
 {
"title": "title", "author": "author", "id": 100, "slug": "slug" 
},....... 
]

 }

try with corrected data it will work.
you can check your data here:http://json.parser.online.fr/

0👍

I saw the problems in your code when you using

 $.each() //It should using for dictionary.

So I have two solutions for you

1) You can use forEach method.

ex:

`if(data != null && data.itemList.length > 0)
{
    data.itemList.forEach(function (item) {
                       a.push("<li>" + item.title + "</li>");
                       });
}` 

==> This way will work for IE 10+, and the other browers.

2) Using the $.each method

ex:

if(data != null && data.itemList.length > 0)
{
   $.each(data.itemList, function (key, item) {
            a.push("<li>" + item.title + "</li>");
    });
}

==> Your Json data is dictionary type, so if you use $.each you need to define two variable with

key: is the key of data.
item: is the value of data.

Note: this way will be worked for all browers version.

Hope this can helps you.

0👍

It’s because your ‘item’ is an index, not an ‘object’ as you want. you have to use the second parameter:

$.each(data.itemList, function (index, item) {
        a.push("<li>" + item.title + "</li>");
});

also, where is hasNextPage defined? is it defined? you might also shorten that to:

if (!hasNextPage) return;
👤Todd

Leave a comment