Populating lists with json

I'm trying to populate list items with JSON, but it doesn't work. Can anyone show me where I went wrong.

<ul style='list-style: none;' id='listSubjet'></ul>

      

var val;
$.ajax({        
    url: 'subjects.json'
}).done(function(d) {
    val = d;
    $.each(val, function(i, su) {
        $('<li data-action = "' + su[0] + '">' + su[1] + '</li>').appendTo('#listSubjet');
    });
});

      

JSON:

[ 
    [ "Science", "Zoology"],
    [ "Science", "Botany"],
    [ "Maths", "Geometry"] 
]

      

EDIT:

error: function(msg){
    console.log('error:', msg)
}

      

enter image description here

+3


source to share


1 answer


The problem could be on the server, if your server is responding with a content type text/plain

then it val = d;

will be a string and not an array. If you can change the content type of your answer to, application/json

or check if there is a string, and if there is JSON.parse

, that string will convert it to an array.

if(typeof d === 'string'){
    val = JSON.parse(d);
}

      



Also you should add this to your ajax: dataType: "json" and only process your response on successful callback

0


source







All Articles