Understanding jQuery jqXHR

I have a set of $.get() requests that I need to refactor to enable the failure callback. Requests have the form

 $.get(url, {}, function(data) {//success, do work //work },'json');//or 'html' 

According to the jQuery API, I just add a jqHXR object. Therefore, in my case, I believe that I should do

 var jqxhr = $.get(url, {}, function(data) {//success, do work //work },'json').error(function() { alert("error"); });//or 'html' 

I do not understand the reason for the second success callback in the example . I suppose it could be there to create a callback chain. I want the error to execute by mistake and the success to succeed. So is that right?

+6
source share
3 answers

I think the second success callback in this example simply illustrates that using this syntax, you can have multiple handlers for the success , error and complete events. In the standard jQuery .ajax() method, you can only assign one handler for each of these events. I can't come up with an example that would require several handlers, but it looks a bit clearer and looks more like the standard jQuery idiom for using

 $.get('my_url.php') .success(handlerOne) .success(handlerTwo); 

instead

 $.get('my_url.php', function(data, textStatus, jqXHR) { handlerOne(data, textStatus, jqXHR); handlerTwo(data, textStatus, jqXHR); }); 

In your case, it might be easier and cleaner to just convert your $.get() statements to $.ajax() . The syntax of $.ajax() is probably better known to most jQuery programmers, and since you don’t need the special functions (multiple handlers, assigning a handler after a request) available in another syntax, there is no reason not to just use $.ajax()

 $.ajax({ url: url, success: function(data) { // success, do work }, error: function(data) { // error, handle failure }, dataType:'json' }); 
+11
source

There is a lot of documentation on this page about how jqXHR (jQuery XHR) differs from XHR (XMLHttpRequest).

http://api.jquery.com/jQuery.ajax/#jqXHR

+4
source

The code you use should be fine. Second success is another place where you can determine the method of success. Some people use the success of jqxhr instead of being passed to $.get() , while others use a handler for processed pending objects to do the same.

+2
source

Source: https://habr.com/ru/post/898539/


All Articles