Understanding jQuery's jqXHR
I have a set of $.get()
requests that I need to refactor to include a failure callback. The requests are of the form
$.get(url,
{},
function(data) {//success, do work
//work
},'json');//or 'html'
According to the jQuery API, I simply add a jqHXR object. So in my case, I believe I should do
var jqxhr = $.get(url,
{},
function(data) {//success, do work
//work
},'json').error(function() { alert("error"); });//or 'html'
I don't understand the reason for the second success callback in the example. I suppose it开发者_如何学C could be there for setting up a callback chain. I want error to execute in error, and success to execute on success. So, is this correct?
I think the second success callback in the example is just there to illustrate that, using this syntax, you can have multiple handlers for success
, error
, and complete
events. In the standard jQuery .ajax()
method, you can only assign a single handler to each of these events. I can't think offhand of an example that would require multiple handlers, but it does seem a little clearer and more like the standard jQuery idiom to use
$.get('my_url.php')
.success(handlerOne)
.success(handlerTwo);
instead of
$.get('my_url.php', function(data, textStatus, jqXHR) {
handlerOne(data, textStatus, jqXHR);
handlerTwo(data, textStatus, jqXHR);
});
In your case, though, it might be easier and cleaner to just convert your $.get()
statements to $.ajax()
. The $.ajax()
syntax is probably more familiar to most jQuery programmers, and since you don't need the special functionality (multiple handlers, post-request handler assignment) available in the other syntax, there's no reason not to just use $.ajax()
:
$.ajax({
url: url,
success: function(data) {
// success, do work
},
error: function(data) {
// error, handle failure
},
dataType:'json'
});
This page has a lot of documentation on how jqXHR (jQuery XHR) differs from XHR (XMLHttpRequest).
http://api.jquery.com/jQuery.ajax/#jqXHR
The code you are using should be fine. The second success is just another place where you can define a success method. Some people use the jqxhr
success instead of the one passed into $.get()
, and others use the deferred object's done handler to do the same.
精彩评论