How can I return value from $.getJSON function? [duplicate]
Possible Duplicate:
How to return value from $.getJSON
function get_url(){
var returnValue = null;
$.getJSON('http://127.0.0.1:1337/?callback=?&command=get_url', "", function(data){
data = $.parseJSON(data);
returnValue = data[0].get_url;
console.log(returnValue); // "not_null"
});
console.log(returnValue); // "null"
return returnValue;
开发者_JAVA百科}
Why function don't return "not_null" ?
The call to $.getJSON
is asynchronous and won't have completed before your get_url
function has returned. There won't be a value in returnValue
to return.
You need to either make the call synchronous by using $.ajax
with async:false
rather than $.getJSON
or handle the return value in an asynchronous manner, modifying the calling logic to not expect it straight away.
$.getJSON
is simply shorthand for a call to $.ajax, so you can do this instead:
$.ajax({
url: url,
dataType: 'json',
data: data,
async: false,
success: callback
});
精彩评论