Jquery:如何在ALL ajax调用上调用回调函数

时间:2021-03-15 20:39:57

is there a way to create in jquery a callback function that is automatically called before ALL ajax request?

有没有办法在jquery中创建一个在所有ajax请求之前自动调用的回调函数?

I need it to check if the session still active but dont want to add it to all 100+ ajax calls i already havecoded on my site.

我需要它来检查会话是否仍然有效,但不想将它添加到我已经在我的网站上编码的所有100多个ajax调用。

3 个解决方案

#1


7  

You could us the .ajaxSetup() method which allows you to register a global beforeSend callback that will be executed before each AJAX call:

您可以使用.ajaxSetup()方法,该方法允许您注册将在每次AJAX调用之前执行的全局beforeSend回调:

$.ajaxSetup({
    beforeSend: function(jqXHR, settings) {
        // ...
    }
});

#2


2  

Use .ajaxSetup() like this

像这样使用.ajaxSetup()

$.ajaxSetup({
    beforeSend: function(jqXHR, settings) {
        // jqXHR is a reference to the jQuery XMLHttpRequest object
    }
});

#3


0  

I am not sure what your condition is to run the jquery callback, but you can search

我不确定你运行jquery回调的条件是什么,但你可以搜索

               .trigger() function

maybe

              $.ajax({
                $(selector).trigger()
              $("selector").ajaxComplete(function(){
                });

               });

#1


7  

You could us the .ajaxSetup() method which allows you to register a global beforeSend callback that will be executed before each AJAX call:

您可以使用.ajaxSetup()方法,该方法允许您注册将在每次AJAX调用之前执行的全局beforeSend回调:

$.ajaxSetup({
    beforeSend: function(jqXHR, settings) {
        // ...
    }
});

#2


2  

Use .ajaxSetup() like this

像这样使用.ajaxSetup()

$.ajaxSetup({
    beforeSend: function(jqXHR, settings) {
        // jqXHR is a reference to the jQuery XMLHttpRequest object
    }
});

#3


0  

I am not sure what your condition is to run the jquery callback, but you can search

我不确定你运行jquery回调的条件是什么,但你可以搜索

               .trigger() function

maybe

              $.ajax({
                $(selector).trigger()
              $("selector").ajaxComplete(function(){
                });

               });