function json (url){
$.getJSON(url, function(data) {
return data;
})
}
this function don’t see “data”
function MakeAlert(){
data = json('action.php');
window.alert(data.name);
}
this work:
function json (url){
$.getJSON(url, function(data) {
window.alert(data.name);
})
}
That’s because the
$.getJSONis asynchronous. It sends the request and returns immediately. Once the server responds (which might be a few seconds later) it invokes thesuccesscallback and that’s why thedatais accessible only inside this callback.If you want to block the caller you could send a synchronous request (note that this might freeze the UI while the request is executing which defeats the whole purpose of AJAX):