Get returned value from function called by getJSON
If $.getJSON()
succeeds in getting the JSON data,开发者_C百科 then a function is called, as shown below. How do I catch the returned value output
?
$.getJSON(url, function(data) {
// Do stuff with data if succeeds in getting the data
return output;
}
);
Since you want to invoke another function when the callback finishes, you should do that in the callback itself. It is invoked asynchronously and the result is not there on the next line. So:
$.getJSON(url, function(data) {
// Do stuff with data if succeeds in getting the data
$.getJSON(data, function() { .. });
}
);
Because the callback is invoked asynchronously you can't deal with the returned value outside the callback.
Rather, inside the callback you need to process the "returned value" by writing it to a give or -- gasp! -- a global variable. :)
the results of the call will be data
$.getJSON(url, function(data) {
// Do stuff with data if succeeds in getting the data
retVal(data);
}
);
function retVal(myVal){
//do stuff here, result is myVal
alert(myVal);
}
edited, last code would not work in any way whatsoever. this one will
var outsideVar;
$.getJSON(url, function(data) {
// Do stuff with data if succeeds in getting the data
outsideVar = data;
}
);
This way you write output into the "global" variable outsideVar (because it is declared outside), so you can access it from anywhere you want.
精彩评论