Java Reference
In-Depth Information
The jqXHR object is called a deferred object; it represents a task that hasn't yet completed. When
you think about it, an asynchronous Ajax request is a deferred task because it doesn't immediately
complete. After you make the initial request, you're left waiting for a response from the server.
jQuery's jqXHR object has many methods that represent different stages of a deferred task, but for
the sake of this discussion, you'll look at only three. They are:
method name
desCription
Executes when the deferred task successfully completes
done()
Executes when the task fails
fail()
Always executes, regardless if the task completed or failed
always()
These methods let you add functions to what are called callback queues —collections of functions
that serve as callbacks for a specified purpose. For example, the done() method lets you add
functions to the “done” callback queue, and when the deferred action successfully completes, all of
the functions in the “done” queue execute.
With this in mind, you can rewrite the previous code like this:
var parms = {
username = "jmcpeak"
};
function handleResponse(obj) {
// obj is already an object
}
var xhr = $.getJSON("phpformvalidator.php", parms);
xhr.done(handleResponse);
Notice that in this code, the handleResponse() function isn't passed to the getJSON() method;
instead, it's added to the “done” queue by passing it to the jqXHR object's done() method. In most
cases, you'd see this code written as follows:
$.getJSON("phpformvalidator.php", parms).done(handleResponse);
You can also chain these method calls to easily add multiple functions to the callback queues:
$.getJSON("phpformvalidator.php", parms)
.done(handleResponse)
.done(displaySuccessMessage)
.fail(displayErrorMessage);
In this example, two functions, handleResponse() and displaySuccessMessage() , are added to
the “done” queue; when the Ajax call successfully completes, both of these functions will execute.
Additionally, this code adds the displayErrorMessage() function to the “fail” queue, and it
executes if the Ajax request fails.
Search WWH ::




Custom Search