我的代码如下。我希望表单在 ajax 函数完成之后提交,这样就可以正确设置 submit
变量。但 submit
始终具有默认的 false
值。如何让表单等待 ajax 调用完成并且为 submit
变量赋予新值?
$("#CreateCandidateForm").on('submit', function (event) {
var theFirstName = $("#FirstName").val();
var theLastName = $("#LastName").val();
var submit = false;
$.ajax({
type: "POST",
url: "CreateSearch", // the method we are calling
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ firstName: theFirstName, lastName: theLastName }),
dataType: "json",
success: function (result) {
if (result == false) {
submit = true;
}
},
error: function (exception) {
event.preventDefault();
console.log(exception);
alert('Exception: ' + exception);
}
});
return submit;
});
最佳答案
jQuery.when() 提供一种基于零个或多个对象(通常是表示异步事件的延迟对象)执行回调函数的方法。
当ajax请求成功时,它会设置submit = true。
$.when( $.ajax({
type: "POST",
url: "CreateSearch",
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ firstName: theFirstName, lastName: theLastName })
})).then(
function(result ){ // Success function
if (result == false) {
submit = true;
}
},function(exception){ // failure function
event.preventDefault();
console.log(exception);
alert('Exception: ' + exception);
});
关于javascript - 如何停止表单提交,直到 onSubmit 调用的 ajax 函数完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37979322/