简体   繁体   English

如何在每个ajax请求上调用特定函数

[英]how to call a specific function on every 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 an ajax request is called a function will called and whenever that request ends another function will call. 我有一个问题,我在我的项目中有几个页面,我在我的项目中使用了很多ajax请求,但现在我认为无论何时调用ajax请求都会调用一个函数,每当该请求结束时,另一个函数将调用。 How can I do this globally I know I can put this in every ajax request but I need a solution which I do in one place and it works all over the project. 我怎么能在全球范围内做到这一点我知道我可以把它放在每个ajax请求中,但我需要一个解决方案,我在一个地方做,它在整个项目中都有效。

$(document).read(function(){
 // Suppose this document load function is written on layout page and every page is  inherited from this page
});

Use ajaxSetup , for example 例如,使用ajaxSetup

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

will setup beforeSend handler for every ajax request. 将为每个 ajax请求设置beforeSend处理程序。 Note that ajaxSetup can take any option that $.ajax can. 请注意, ajaxSetup可以采用$.ajax可以选择的任何选项。

You should create a wrapper function for your ajax, then use that function. 您应该为ajax创建一个包装函数,然后使用该函数。 that way, you have "central" control over the ajax call. 这样,你就可以对ajax调用进行“集中”控制。 something like: 就像是:

//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
});

.ajaxStart .ajaxStart

Register a handler to be called when the first Ajax request begins. 注册第一个Ajax请求开始时要调用的处理程序。

.ajaxSucess .ajaxSucess

Attach a function to be executed whenever an Ajax request completes successfully. 附加要在Ajax请求成功完成时执行的函数。

for Detail doc: http://api.jquery.com/category/ajax/ 详情doc: http//api.jquery.com/category/ajax/

Try something like this: 尝试这样的事情:

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

That means whenever ajax call completed successfully call your desire call. 这意味着无论何时ajax呼叫成功呼叫您的欲望呼叫。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM