如何知道 jQuery 是否有一个 Ajax 请求挂起?

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

问题是,当普通用户输入一个无效的值,并且通过按下提交按钮而失去焦点时,jQuery 帖子会在表单提交完成后返回。

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

107594 次浏览

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:

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

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

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. :)

You could use ajaxStart and ajaxStop to keep track of when requests are active.

$.active returns the number of active Ajax requests.

More info here

 $(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);
});

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

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

//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 () {


}
});