Josef Lundström Josef Lundström -4 years ago 93
jQuery Question

Update: How do I dynamically populate a list with data from a JSON file?

I want to dynamically populate a list with elements from a JSON file. The idea is to switch the test_ID in the list with the actual object from the JSON file. How do I do this?

JSON file

[
{
"id": "a",
"test": "Java",
"testDate": "2016-08-01"
},
{
"id": "b",
"test":"JavaScript",
"testDate": "2016-08-01"
}
]


jQuery

$(function(){

$.ajax({
type : 'GET',
url : 'json/data.json',
async : false,
beforeSend : function(){/*loading*/},
dataType : 'json',
success : function(result) {
});

$("#test_ID").empty(); //emtpy the UL before starting
$.each(arr_json, function(i, v, d) {
$("#test_ID").append("<li id='" + v.id +'" + v.test +"' >" + v.testDate + "<li>");
});
}
});
});


HTML

<li id="test_ID"></li>


I do receive a couple of errors. The Line:

$("#test_ID").append("<li id='" + v.id +'" + v.test +"' >" + v.testDate + "<li>");


gives the following error: invalid number of arguments and unclosed String literal.
I am also unsure of how to identify to specific elements in the JSON file.

Update
I would like if the list element was in this format "Java 2016-08-01" and "JavaScript 2016-08-01". Thank you!

Answer Source

You have a couple of errors in your javascript. See the corrected version below:

 $(function(){
   $.ajax({
     type : 'GET',
     url : 'json/data.json',
     async : false,
     beforeSend : function(){/*loading*/},
     dataType : 'json',
     success : function(result) {
            $("#test_ID").empty(); //emtpy the UL before starting

            // **************** correction made to the line below ***********************
            $.each(result, function(i, v, d) {                        

            // **************** correction made to the line below ***********************
            $("#test_ID").append('<li id="' + v.id + '">' + v.test + '  ' + v.testDate + '</li>');                         // correction made here
        });
    }
   });
 });
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download