Form OnSubmit to wait jQuery Ajax Return?(表单 OnSubmit 等待 jQuery Ajax 返回?)
问题描述
我想在 onsubmit
表单上触发 $.ajax
并且只有在 Ajax 返回有效之后才return true
.
I want to trigger $.ajax
on form onsubmit
and return true
only after Ajax return is something valid.
例如:
<form id="myForm" onsubmit="return ajaxValidation();">
<input id="myString" name="myString" type="text" />
<input type="submit" value="Submit" />
</form>
在 Javascript 中:
In 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
行.
When i submit, i got alert ok
, but it returned 'false' because it jumped to final return false
line.
为什么?我不明白.实际上,它应该到达 return true
行.(而且,即使在 return true
之后,该函数也应该停在那里并从中退出)
Why? I can not understand. Actually, it should hit to return true
line. (And, even after return true
, the function should stop there and just come out of it)
现在的意思是,父函数不等待
到Ajax Return.相反,它不断地运行到最后.知道为什么,请.如何让父函数等待Ajax?
So it is now means, the parent function does NOT wait
to the Ajax Return. Instead, it is continuously running down to the end. Any idea why, please. How to make the parent function to be waiting the Ajax?
推荐答案
由于 AJAX 是异步的,因此在提交按钮上使用单击处理程序会更好.
Since AJAX is asynchronous your validation Would work better using a click handler on the submit button.
以下是基于删除内联onSubmit
$(function() {
var $form = $('#myForm');
$form.find('input[type="submit"]').click(function() {
$.ajax({
/* async: false, this is deprecated*/
type: "POST",
url: "ajax.php",
data: {
myString: $("#myString").val()
}
}).success(function(response) {
alert(response); //Got 'ok'
if(response == "ok") {
/* submit the form*/
$form.submit();
} else {
alert("Oh, string is wrong. Form Submit is cancelled.");
}
}); /* prevent default when submit button clicked*/
return false;
});
});
这篇关于表单 OnSubmit 等待 jQuery Ajax 返回?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:表单 OnSubmit 等待 jQuery Ajax 返回?


基础教程推荐
- Node.js 有没有好的索引/搜索引擎? 2022-01-01
- 如何使用 CSS 显示和隐藏 div? 2022-01-01
- 每次设置弹出窗口的焦点 2022-01-01
- 如何使用sencha Touch2在单页中显示列表和其他标签 2022-01-01
- 如何在特定日期之前获取消息? 2022-01-01
- 为什么我在 Vue.js 中得到 ERR_CONNECTION_TIMED_OUT? 2022-01-01
- Javascript 在多个元素上单击事件侦听器并获取目标 2022-01-01
- 什么是不使用 jQuery 的经验技术原因? 2022-01-01
- jQuery File Upload - 如何识别所有文件何时上传 2022-01-01
- WatchKit 支持 html 吗?有没有像 UIWebview 这样的控制器? 2022-01-01