场景
表单中有两个输入框input在提交这个表单前需要对两个输入框进行校验。
即点击提交按钮时会经过校验的方法,此方法会post方式提交到后台,在请求后台成功后的回调方法中会对js变量进行赋值,进而决定是否提交此表单。
$.post
默认是异步提交,所谓异步提交就是在请求发出去之后,不管结果是否返回,都会执行后面的代码。
所以呀想把返回的结果或者根据返回结果给js变量赋值,那么就要使用同步请求。同步请求就是等请求结果返回后再执行后面的代码。
因为默认是异步请求,所以修改为同步请求的方式为:
async:false,
添加如上属性。
实现
form表单代码:
<form id="inAirportForm" action="${ctx}/frontPage/passFlight/GJbook.html" method="post" class="plug_form dis_none" onsubmit="return inAirportCheck(this)">
<button class="btn_max wm_94 bg_title c_white mt_1em h_36em"
type="submit"><spring:message code="search" /></button>
<button
class="btn_max wm_94 border bor_title bg_white c_title mt_1em h_36em"
type="reset"><spring:message code="reselection" /></button>
</div>
</form>
中间input框代码省掉。
js验证方法代码
function inAirportCheck(that) {
var guojiStrart = $(".plug_airport3 ").val();
var guojiEnd = $(".plug_airport4").val();
debugger
var formAction = "${ctx}/frontPage/passAddrAirport/validateIsGuoNeiAll";
var validateIsGuoNeiAll = false;
$.post({
async:false,
url: formAction,
cache: false, //禁用缓存
data:JSON.stringify({"guojiStrart":guojiStrart,"guojiEnd":guojiEnd}),
contentType: "application/json",
dataType: "json",
success: function (result) {
debugger
if ("300" == result.statusCode) {
$ak.alert(result.message, { //(微信平台的H5使用方法 $ak.alert)
title: "信息提示",//弹窗标题
button_ok: "确定",
button_cancel: "取消",
icon: "error", //图标类型(warning,error,info,question,success)
animateIn: "bounceInDown",//弹窗显示效果
animateOut: "bounceOutUp"
});
validateIsGuoNeiAll = false;
}
if("200" == result.statusCode){
validateIsGuoNeiAll = true;
}
}
});
return validateIsGuoNeiAll;
}
如上代码是设置为同步之后的代码,如果不加async:false,< BR> 则后台还没走完验证,表单已经提交。