【发布时间】:2013-01-10 13:39:25
【问题描述】:
我想在表单onsubmit 和return true 上触发$.ajax,只有在Ajax 返回有效之后。
例如:
<form id="myForm" onsubmit="return ajaxValidation();">
<input id="myString" name="myString" type="text" />
<input type="submit" value="Submit" />
</form>
在 Javascript 中:
function ajaxValidation() {
$.ajax({
async: false,
type: "POST",
url: "ajax.php",
data: { myString: $("#myString").val() }
}).success(function( response ) {
alert(response); //Got 'ok'
if (response=="ok") {
return true; //mark-1
} else {
alert("Oh, string is wrong. Form Submit is cancelled.");
}
});
return false; //mark-2
}
当我提交时,我收到了警报 ok,但它返回了“false”,因为它跳转到了最后一行 return false。
为什么?我不明白。实际上,它应该打到return true 行。 (而且,即使在return true 之后,该函数也应该停止在那里并从中退出)
所以现在的意思是,父函数does NOT wait 向Ajax 返回。相反,它不断地运行到最后。请知道为什么。如何让父函数等待Ajax?
【问题讨论】:
-
只有一个 return 会影响 ajaxValidation 函数,即标记为 2 的返回,其余在另一个函数中。
标签: jquery ajax asynchronous return onsubmit