why return JSON object is undefine by calling function?
script :
$(document).ready(function() {
var userdata = getData();
};
function getData() {
var udata;
$.getJSON(‘../json/user.json’, function(data) {
udata = data;
});};
Reason: $.getJSON ( is async, which it might run later than it call getData();
Solution 1: disable async
$(document).ready(function() {
var userdata = getData();
};function getData() {
var udata;
$.ajax({
async: false,
url: ‘../json/user.json’,
dataType: ‘json’,
success: function(response) {
udata = response;
}
});
};
——————Solution 2: pass in callback
$(document).ready(function() {
getData(function(data) {
});
};function getData() {
$.getJSON(‘../json/user.json’, callback, function(udata) {});
};
ref: http://stackoverflow.com/questions/4546339/jquery-assign-json-as-a-result-to-a-variable