JQuery: is there a difference between $ .ajaxSetup (beforeSend) and $ (document) .ajaxSend?

Using jQuery (v2.1.4), is there a difference between the two methods?

1) $. ajaxSetup (beforeSend)

$.ajaxSetup({
  beforeSend: function (jqXHR, settings) {
    // whatever you need to do before
    // any jQuery Ajax request is sent
  }
});

2) $ (document) .ajaxSend

$(document).ajaxSend(function (event, jqXHR, settings) {
  // whatever you need to do before
  // any jQuery Ajax request is sent
});

Is there any reason to prefer each other?

Thanks!

+4
source share
3 answers

From jQuery $.ajaxSetup()documentation:

All subsequent Ajax calls using any function will use the new settings, unless overridden by individual calls, until the next call to $ .ajaxSetup ().

$.ajaxSetup() does something like this:

ajaxExtend(jQuery.ajaxSettings, target);

From the $.ajaxSend()documentation:

, Ajax, jQuery ajaxSend. , .ajaxSend(), .

jQuery $.ajaxSend():

function (fn) {
    return this.on(type, fn);
}

, $(document).ajaxSend() , , jQuery Ajax ( , XMLHttpRequest.readyState 1 - "" ).

, $.ajax() global, false, ajaxSend() .

$.ajaxSetup() jQuery Ajax , beforeSend (XMLHttpRequest.readyState 0 - "Unsent" ).

+2

, ,

  • ajaxSend() .
  • $.ajax() , false, ajaxSend() .
  • beforeSend .

ajaxSend, ajax beforeSend $.ajax().

HTML

<body>

<div><h2>Let AJAX change this text</h2></div>

<button id="btn1">Change Content</button>
<button id="btn2">Change Content Override</button>

</body>

JS

   $(document).ajaxSend(function(e, xhr, opt){
        $("div").append("<p>Requesting " + opt.url + "</p>");
    });
    $("#btn1").click(function(){
        $("div").load("yourpage.html");
    });
    $("#btn2").click(function(){
        $.ajax({
        global: false,
        beforeSend:function(){$("div").append("<p>Overriding</p>");}
        });
    $("div").load("yourpage.html");
    });

LIVE http://jsfiddle.net/mailmerohit5/w8t44247/

0

JQuery:

:

    , Ajax    , :

 $.ajax({
     beforeSend: function(){
     // Handle the beforeSend event
  },
     complete: function(){
     // Handle the complete event
  }
  // ......
});

, , . :

$(document).bind("ajaxSend", function(){
   $("#loading").show();
 }).bind("ajaxComplete", function(){
   $("#loading").hide();
 });

Ajax, , :

$.ajax({
    url: "test.html",
    global: false,
    // ...
});

0

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


All Articles