Comparison of jQuery getJSON and ajax.
I tried to debug this code in jQuery(the following), the object is to get the data from a json file and re-format the output data into an array, this array will be used in others functions later.
$(document).ready(function() { var arr = []; // Get data from a json file $.getJSON("jsonfile.json", {}, function(data) { $.each(data, function(key, value) { arr.push(value); // Add data value to an array }); }); console.log(arr); // Print the array to console });
Whatever the methods I try, the console still cannot display the data.
At the beginning, I thought that it was a problem of the scope of variable in javascript, so I removed the “var” before the variable arr to make it global, not working. And I added the variable to the “window”, still not working. Boring …
Three hours later …
Just before I gonna to give up, I tried the function ajax, surprised, it works!
$(document).ready(function() { var arr = []; // Get data from a json file $.ajax({ url: "jsonfile.json", async: false, dataType: 'json', success: function(data) { $.each(data, function(key, value) { arr.push(value); }); } }); console.log(arr); // Print the array to console });
…
Finally I found the raison :
– The function getJSON is asynchronized, without get the response, the following code will be executed.
– The function ajax CAN BE synchronized, just give the async option to false.
So return back to my function (with new comments):
$(document).ready(function() { var arr = []; // 1st execute $.getJSON("jsonfile.json", {}, function(data) { // 2nd execute $.each(data, function(key, value) { arr.push(value); // 4th execute }); }); console.log(arr); // 3rd execute });
getJSON won’t wait the response and continue execute the following code, that why I always cannot get my array value.
Hope it helps !