我怎么知道 jQuery 是否有一个 Ajax 请求待处理?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1822913/
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 12:13:03  来源:igfitidea点击:

How do I know if jQuery has an Ajax request pending?

jqueryajaxxmlhttprequest

提问by sabanito

I'm having some problems with a jQuery control we made. Suppose you have a dropdownlist that allows you to enter the ID of the item you're looking for, and when you press ENTER or lose focus in a textbox it validates via jQuery that the ID you entered is correct, showing an alert if it doesn't.

我在我们制作的 jQuery 控件上遇到了一些问题。假设您有一个下拉列表,允许您输入要查找的项目的 ID,当您按 ENTER 或在文本框中失去焦点时,它会通过 jQuery 验证您输入的 ID 是否正确,如果不正确则显示警报'不。

The thing is that when an ordinary user enters an invalid value in it and loses focus by pressing the submit button, the jQuery post returns after the submit of the form has been sent.

问题是当普通用户在其中输入无效值并通过按下提交按钮失去焦点时,jQuery post 在表单提交后返回。

Is there any way that I can check if there's any Async request processing by jQuery so that I do not allow the form submit?

有什么方法可以检查jQuery是否有任何异步请求处理,以便我不允许提交表单?

采纳答案by ceejayoz

You could use ajaxStartand ajaxStopto keep track of when requests are active.

您可以使用ajaxStartajaxStop来跟踪请求何时处于活动状态。

回答by sivabudh

$.activereturns the number of active Ajax requests.

$.active返回活动 Ajax 请求的数量。

More info here

更多信息在这里

回答by etgregor

 $(function () {
        function checkPendingRequest() {
            if ($.active > 0) {
                window.setTimeout(checkPendingRequest, 1000);
                //Mostrar peticiones pendientes ejemplo: $("#control").val("Peticiones pendientes" + $.active);
            }
            else {

                alert("No hay peticiones pendientes");

            }
        };

        window.setTimeout(checkPendingRequest, 1000);
 });

回答by Toji

The $.ajax() function returns a XMLHttpRequest object. Store that in a variable that's accessible from the Submit button's "OnClick" event. When a submit click is processed check to see if the XMLHttpRequest variable is:

$.ajax() 函数返回一个 XMLHttpRequest 对象。将其存储在可从提交按钮的“OnClick”事件访问的变量中。处理提交单击时,检查 XMLHttpRequest 变量是否为:

1) null, meaning that no request has been sent yet

1) null,表示还没有发送请求

2) that the readyState value is 4 (Loaded). This means that the request has been sent and returned successfully.

2)readyState 值为 4(已加载)。这意味着请求已成功发送并返回。

In either of those cases, return true and allow the submit to continue. Otherwise return false to block the submit and give the user some indication of why their submit didn't work. :)

在任何一种情况下,返回 true 并允许提交继续。否则返回 false 以阻止提交并为用户提供一些说明为什么他们的提交不起作用。:)

回答by vibs2006

We have to utilize $.ajax.abort()method to abort request if the request is active. This promise object uses readyStateproperty to check whether the request is active or not.

如果请求处于活动状态,我们必须使用$.ajax.abort()方法来中止请求。这个 promise 对象使用readyState属性来检查请求是否处于活动状态。

HTML

HTML

<h3>Cancel Ajax Request on Demand</h3>
<div id="test"></div>
<input type="button" id="btnCancel" value="Click to Cancel the Ajax Request" />

JS Code

JS代码

//Initial Message
var ajaxRequestVariable;
$("#test").html("Please wait while request is being processed..");

//Event handler for Cancel Button
$("#btnCancel").on("click", function(){
if (ajaxRequestVariable !== undefined)

if (ajaxRequestVariable.readyState > 0 && ajaxRequestVariable.readyState < 4)
{
  ajaxRequestVariable.abort();
  $("#test").html("Ajax Request Cancelled.");
}
});

//Ajax Process Starts
ajaxRequestVariable = $.ajax({
            method: "POST",
            url: '/echo/json/',
            contentType: "application/json",
            cache: false,
            dataType: "json",
            data: {
        json: JSON.encode({
         data:
             [
                            {"prop1":"prop1Value"},
                    {"prop1":"prop2Value"}
                  ]         
        }),
        delay: 11
    },

            success: function (response) {
            $("#test").show();
            $("#test").html("Request is completed");           
            },
            error: function (error) {

            },
            complete: function () {

            }
        });