I'm using a json api to create an array of data. For each item I want to create a html block to add to a list and append to a container. The following code works:
var url = "https://myjsonurl.json",
array = [],
html = "<ul class='card'>";
$.getJSON(url, function( res ) {
array = res.badges;
$.each(array, function(index, item) {
html += "<li>HTMLblock</li>";
});
html += "</ul>";
$("#reportCard").append(html);
});
However, the following code does not:
var url = "https://myjsonurl.json",
array = [],
html = "<ul class='card'>";
$.getJSON(url, function( res ) {
array = res.badges;
});
$.each(array, function(index, item) {
html += "<li>HTMLblock</li>";
});
html += "</ul>";
$("#reportCard").append(html);
This may be quite obvious but I can't understand why the last example will not work when the array and card variables are declared before the .getJSON call?