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 返回?


- 使用RSelum从网站(报纸档案)中抓取多个网页 2022-09-06
- Css:将嵌套元素定位在父元素边界之外一点 2022-09-07
- Fetch API 如何获取响应体? 2022-01-01
- Flexslider 箭头未正确显示 2022-01-01
- Quasar 2+Apollo:错误:找不到ID为默认的Apollo客户端。如果您在组件设置之外,请使用ProvideApolloClient() 2022-01-01
- addEventListener 在 IE 11 中不起作用 2022-01-01
- 失败的 Canvas 360 jquery 插件 2022-01-01
- 400或500级别的HTTP响应 2022-01-01
- 如何使用 JSON 格式的 jQuery AJAX 从 .cfm 页面输出查 2022-01-01
- CSS媒体查询(最大高度)不起作用,但为什么? 2022-01-01