jQuery 如何在每次 ajax 调用之前和之后触发某些操作

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4898381/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 18:09:29  来源:igfitidea点击:

How to fire certain action before and after every ajax call

jqueryajaxjquery-ui

提问by Pascal Klein

I'm using jQuery and jQuery UI. I experienced that users sometimes fire the ajax-calls more than once, because the button/Link that triggers the call is not disabled right after they click it. To prevent that from happen, I now disable the button/link in my "beforeSend" -action.

我正在使用 jQuery 和 jQuery UI。我经历过用户有时会多次触发 ajax 调用,因为触发调用的按钮/链接在他们点击后没有立即禁用。为了防止这种情况发生,我现在禁用“beforeSend”-action 中的按钮/链接。

This is what a typical Ajax Call looks like for me:

对我来说,典型的 Ajax 调用是这样的:

   $.ajax({
      type: "POST",
      url: "someURL"
      data: "someDataString",
      beforeSend: function(msg){
        $(".button").button("disable");
      },
      success: function(msg){
        $(".button").button("enable");
        // some user Feedback
      }
    });

But I dont wann to add this button-Disable logic in every Ajax Call. Is there any way to globally define a function that gets called everytime before /after and ajax-call?

但我不想在每个 Ajax 调用中添加这个按钮禁用逻辑。有没有办法全局定义一个每次在/之后和ajax调用之前都被调用的函数?

回答by mekwall

There are several ways to achieve what you are asking for. The only difference between them is how they are implemented, and it's up to you to choose which method works best for your specific case. The methods also depend on which version of jQuery you are using, so I will split this answer into two sections.

有几种方法可以实现您的要求。它们之间的唯一区别是它们的实现方式,您可以选择哪种方法最适合您的特定情况。这些方法还取决于您使用的 jQuery 版本,因此我将把这个答案分成两部分。

For jQuery 1.5 and later

对于 jQuery 1.5 及更高版本

Adding multiple callbacks after init

init 后添加多个回调

Since jQuery 1.5 you can add multiple callbacks thanks to the overhauled API and newly introduced jqXHRobject that is returned by .ajax. It implement the Promise (see Deferreds) interface, and we can use that to our advantage:

从 jQuery 1.5 开始,您可以添加多个回调,这要归功于经过大修的 API 和jqXHR.ajax. 它实现了 Promise(参见Deferreds)接口,我们可以利用它来发挥我们的优势:

// fn to handle button-toggling
var toggleButton = function() {
    var button = $(".button");
    button.button(button.button("option", "disabled") ? "enable" : "disable");
}

// store returned jqXHR object in a var so we can reference to it
var req = $.ajax({
    beforeSend: toggleButton,
    success: function(msg){
        /* Do what you want */
    }
}).success(toggleButton);

// we can add even more callbacks
req.success(function(){ ... });

Using a prefilter

使用预过滤器

jQuery 1.5 also introduced prefilterswhich you can use to replace the global configuration of jQuery 1.4:

jQuery 1.5 还引入了预过滤器,您可以使用它来替换 jQuery 1.4 的全局配置:

// good practice: don't repeat yourself, especially selectors
var button = $(".button");

$.ajaxPrefilter(function(options, _, jqXHR) {
    button.button("disable");
    jqXHR.complete(function() {
        button.button("enable");
    });
});

Note: The jqXHR section of the $.ajax entryhas this notice about using jqXHR.success():

注意:$.ajax 条目jqXHR 部分有关于使用的注意事项jqXHR.success()

Deprecation Notice: The jqXHR.success(), jqXHR.error(), and jqXHR.complete() callbacks are deprecated as of jQuery 1.8. To prepare your code for their eventual removal, use jqXHR.done(), jqXHR.fail(), and jqXHR.always() instead.

弃用通知:jqXHR.success()、jqXHR.error() 和 jqXHR.complete() 回调从 jQuery 1.8 开始弃用。要为最终删除代码做好准备,请改用 jqXHR.done()、jqXHR.fail() 和 jqXHR.always()。

For jQuery 1.4 and earlier

对于 jQuery 1.4 及更早版本

Events and global configuration

事件和全局配置

Use .ajaxStartand .ajaxStopto bind callbacks to a specific selector. The events that trigger these callbacks will fire off on all Ajax requests.

使用.ajaxStart.ajaxStop将回调绑定到特定选择器。触发这些回调的事件将触发所有 Ajax 请求。

$(".button").ajaxStart(function(){
    $(this).button("disable");
}).ajaxStop(function(){
    $(this).button("enable");
});

Use .ajaxSetupto setup a global ajax configuration. The settings object passed to .ajaxSetupwill be applied to all Ajax requests, even those made by the shorthands .get, .getJSONand .post. Note that this isn't recommended since it can easily clobber its functionality.

使用.ajaxSetup设置一个全局AJAX配置。传递给的设置对象.ajaxSetup将应用于所有 Ajax 请求,即使是那些由简写.get,.getJSON.post. 请注意,不建议这样做,因为它很容易破坏其功能。

$.ajaxSetup({
    beforeSend: function(){
        $(".button").button("disable");
    },
    success: function(){
        $(".button").button("enable");
    }
});

Filter out requests in global event callbacks

过滤掉全局事件回调中的请求

If you need to filter out certain requests you can do that with.ajaxSendand .ajaxCompletewhere you can check the Ajax settingsobject. Something like this:

如果您需要过滤掉某些请求,您可以使用它.ajaxSend以及.ajaxComplete可以检查 Ajaxsettings对象的位置。像这样的东西:

var button = $(".button");

// fn to handle filtering and button-toggling
var toggleButton = function(settings) {
    if (settings.url == "/specific/url")
        button.button(button.button("option", "disabled") ?
            "enable" : "disable");
    }
};

// bind handlers to the callbacks
button.ajaxSend(function(e,x,settings){
    toggleButton(settings);
}).ajaxComplete(function(e,x,settings){
    toggleButton(settings);
});

This can also be done with the previously mentioned .ajaxSetupby doing the same type of checks to the settingsobject that is passed to the callback handlers.

这也可以通过前面提到.ajaxSetup的对settings传递给回调处理程序的对象执行相同类型的检查来完成。

回答by Caspar Kleijne

To register them globallyuse the

全局注册它们,请使用

ajaxStartor ajaxSendevents

ajaxStartajaxSend事件

together with the

ajaxCompleteor ajaxStopevent

ajaxCompleteajaxStop事件

$(".button").ajaxStart(function(){
      $(this).attr("disabled","disabled");
});


$(".button").ajaxStop(function(){
      $(this).attr("disabled","");
});

回答by Brian Ball

Yes, you can set defaults for all ajax calls by calling this function for each page: http://api.jquery.com/jQuery.ajaxSetup/

是的,您可以通过为每个页面调用此函数来设置所有 ajax 调用的默认值:http: //api.jquery.com/jQuery.ajaxSetup/

Also, if there is an ajax call that you don't want to use the default, then simply define that option for that particular ajax call.

此外,如果有一个您不想使用默认值的 ajax 调用,那么只需为该特定 ajax 调用定义该选项。

回答by Rob

You could try and bind an eventhandler to the submit event and call an action every time the submit action is called. Read about it here. Otherwise AjaxSetupis another good way to do the trick.

您可以尝试将事件处理程序绑定到提交事件,并在每次调用提交操作时调用一个操作。在这里阅读。否则,AjaxSetup是另一种实现技巧的好方法。