When I do this:
$.ajax({
url: purl,
dataType: 'json',
success: function(data){
alert(data.length);
}
});
I get an alert with the length count.
but when I do this…
$.ajax({
url: purl,
dataType: 'json',
success: function(data){
items = data.length;
}
});
alert(items);
Setting length to global varialbe, it doesn’t want to play nice. Thoughts?
The AJAX portion doesn’t happen instantaneously; the
alerttakes place before the AJAX callback has time to set the new value foritems.As of jQuery 1.5,
$.ajaxreturns an object that implements the Promises interface. As such, you can call the.donemethod anytime you need to be sure that the promise has resolved prior to executing your code:As an example, suppose we created a deferred object directly:
We then told it not to resolve until after five seconds:
But then we bound a handler to respond to clicks on the
documentobject:Note that we are putting our alert within an anonymous function, and passing it to
promise.doneto be executed only after the promise has been resolved.This builds up a queue until that promise is resolved. If I click four times in those first five seconds, nothing will happen, but as soon as that promise resolves I will see four alert boxes appear, one after another.
Now that the promise is resolved, any further clicks (after the 5 second wait) will result in immediate action.
Demo: http://jsfiddle.net/w7swE/1/