How to call a specific function for each ajax request

I have a problem that I have several pages in my project and I used a lot of ajax requests in my project, but now I think that whenever the ajax request is called, the function is called, and whenever this request finishes I’ll call another function. How can I do this globally I know that I can put this on every ajax request, but I need a solution that I make in one place and it works throughout the project.

$(document).read(function(){
 // Suppose this document load function is written on layout page and every page is  inherited from this page
});
+5
source share
4 answers

Use ajaxSetup e.g.

$.ajaxSetup({
    beforeSend: function() {
        console.log('test');
    },
    complete: function() {
        console.log('completed');
    }
});

beforeSend ajax. , ajaxSetup , $.ajax.

+5

- ajax, . , "" ajax. - :

//fast and crude way to extend jQuery
$.fn.customAjax = function(params){

    //contains defaults and predefined functions
    var defaults = {
        complete : function(){...default complete hander...},
        beforeSend : function (){...default beforeSend handler}
        ...
    }

    //merge settings
    var finalParams = $.extend({},defaults,params);

    //call ajax and return the deferred
    return $.ajax(finalParams);
}

//use it like
$.customAjax({
   url : ...,
   method : ...,
   data: ...,
   complete : function(){...} //redefining in the call will override the defaults
});
+2

.ajaxStart

, , Ajax.

.ajaxSucess

, , Ajax .

:   http://api.jquery.com/category/ajax/

+1

- :

$.ajax({
  url: "test.html",
  context: document.body
}).done(function() { 
   $.ajax({
     url: "anotherMethod.html",
     context: document.body
   });
});
});

, , ajax- , .

0
source

All Articles