gpt4 book ai didi

javascript - 如何在 $.ajax 调用后停止执行 JS 代码,即当服务器正在处理 AJAX 请求时

转载 作者:行者123 更新时间:2023-11-28 16:07:54 25 4
gpt4 key购买 nike

我在 JQuery AJAX 中遇到一个奇怪的问题..

我的步骤顺序如下:

1) 我有一个 JS 函数,我在按钮单击事件上调用它:

 function Click()
{

//I am performing some Validations then making an AJAX Request:

$.ajax({
type: "POST",
url: url,
context: window,
data: datatoPost,
contentLength: contentLength,
async: true,
success: function (response) {
callbackFn(response);
},
error: function (msg) {
this.error = msg;
}
});

// The callback function is called on Successfull AJAX Request
// i.e. callbackFn (See below)

// I am then checking the window.IsValid which I have set in below function;

if (window.IsValid == true) {
// Then Perform another AJAX Request
}
else {
// do nothing
}
}


function callbackFn(response)
{
if(response == 'Valid')
{
window.IsValid = true;
}
else
{
window.IsValid = false;
}
}

2) 现在,问题是服务器正在处理第一个 AJAX 请求,然后是之后编写的代码,即 if (window.IsValid == true) { //然后执行另一个 AJAX 请求 } 别的 { //没做什么 } }已执行

3) 我得到 window.IsValid = false 作为第一个 AJAX 请求的回调函数,即 callbackFn(response) 尚未调用,即使在第一个 AJAX 的有效响应之后请求我的第二个ajax请求没有被执行,因为window.IsValid变量仍然没有在回调函数中设置,因为由于服务器正在处理请求,回调尚未被调用。

请帮助我,我被困住了..

最佳答案

然后你应该使用

async: false,

在你的ajax函数调用中。这是不推荐的。更好的办法是使用

if (window.IsValid == true) {
// Then Perform another AJAX Request
}
else {
// do nothing
}
}

在您的回调函数中。

关于javascript - 如何在 $.ajax 调用后停止执行 JS 代码,即当服务器正在处理 AJAX 请求时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14124956/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com