【发布时间】:2021-05-04 19:48:27
【问题描述】:
我正在寻找一种方法来修改在回调之外声明的变量,然后在定义回调后使用修改后的变量。我的意图反映在代码中:
$('#my_form').submit(function() {
let my_condition
let data = $(this).serialize()
$.ajax({
method: 'POST',
url: '/my_url',
data: data
})
.done(function(json_response) {
if (json_response.my_variable) {
my_condition = true
}
else {
my_condition = false
}
})
// I'm looking for a way to guarantee `my_condition` is set by the AJAX before the below code is run.
if (my_condition) { // I know `my_condition` will be null because this line won't wait for the AJAX to finish and set `my_condition`.
return true
}
else { // The event handler will always hit this condition.
return false
}
})
我知道我可以在检查 my_condition 之前添加阻塞睡眠时间以等待 AJAX。这不是我正在寻找的解决方案。我也知道我可以在前端检查data 的基础上设置my_condition。但是,由于特定于我的用例的原因,data 需要在后端处理。最后,我想避免 AJAX 设置async: false。
我知道为什么上面的代码不起作用。我的问题是,有什么方法可以达到预期的效果吗?我感觉可能有一个使用 Promise 的解决方案,但我不知道该怎么做。
编辑 1:具体用例与表单提交有关。我希望提交处理程序返回 true 或 false,即根据数据的后端处理结果通过表单的操作属性(当 my_condition 为 true 时)或不同的 (AJAX) 路由(当 my_condition 为 false 时)提交。
编辑 2:这确实是 Javascript - Stop form submit depending on ajax response [duplicate] 的副本
【问题讨论】:
-
你不能这样编程。 ajax 调用是非阻塞和异步的。这意味着您的
if (my_condition)在.done()调用回调之前执行,因此您尝试在设置之前使用my_condition值。 -
谢谢。是的,正如我所提到的,我知道为什么代码不起作用。我的问题是是否有不同的模式,也许使用 Promise,能够达到相同的效果。
-
@Andrew 这是不可能的(不使用同步 XHR)。相反,始终阻止提交事件的默认操作,然后当服务器响应是肯定的时执行
.submit()表单。 -
@Bergi 谢谢,我不知道 preventDefault。
-
@Andrew 这基本上就是 jQuery 事件处理程序中的
return false所做的
标签: javascript jquery ajax promise callback