今天工作中遇到一个BUG.
js方法ajax验证名字是否存在,存在就不继续发post请求。
之前错误的代码:
function isRoleExists() {
$.ajax({
url: '@Url.Action("IsRoleExists")',
type: "GET",
cache: false,
data: { "roleName": $("#RoleName").val(), "selfName": "" },
success: function (data) {
if (data == "True") {
alert('Role had already exists !');
$("#RoleName").addClass("input-validation-error");
return true;
}
else {
$("#RoleName").removeClass("input-validation-error");
return false;
}
}
});
}
//3.validate exists or not
if (isRoleExists()) {
return false;
}
//4.ajax post, if not exists and form is validate
addRole();
错误原因,在$.ajax方法的success方法中return,影响的是ajax方法是否进行下一步,返回值的作用域是ajax方法。
函数isRoleExists,所以isRoleExists函数始终返回undifined, ajax返回返回true或false不会影响到它。所以语句if (isRoleExists()) {始终为false,走不到return false语句,所以尽管提示名称已经存在,还是发post请求了。修改后的方法:
function isRoleExists() {
var _flag = true;
$.ajax({
url: '@Url.Action("IsRoleExists")',
type: "GET",
cache: false,
data: { "roleName": $("#RoleName").val(), "selfName": "@Model.RoleName" },
success: function (data) {
if (data == "True") {
alert('Role had already exists !');
$("#RoleName").addClass("input-validation-error");
}
else {
$("#RoleName").removeClass("input-validation-error");
flag= false;
}
}
});
return _flag;
}
这样,当名称存在时候,最终返回的_flag值为ture时,if (isRoleExists()) {语句为ture,执行return false语句,不会去发post请求。
发现有bug,不重复的也不能提交。原因是ajax scucess执行时间要晚,return语句不等ajax执行完,就执行了。
function isRoleExists() {
var _isExists = true;
$.ajax({
url: '@Url.Action("IsRoleExists")',
type: "GET",
cache: false,
data: { "roleName": $("#RoleName").val(), "selfName": "" },
success: function (data) {
if (data == "True") {
alert('Role had already exists !');
$("#RoleName").addClass("input-validation-error");
}
else {
$("#RoleName").removeClass("input-validation-error");
_isExists = false;
}
$("#sp1").html("ajax call time :Second:" + new Date().getSeconds() + " ,Millisecond:" + new Date().getMilliseconds());
}
});
$("#sp2").html("fun call time :Second:" + new Date().getSeconds() + " ,Millisecond" + new Date().getMilliseconds());
return _isExists;
}
结果:ajax call time :Second:30 ,Millisecond:642
fun call time :Second:30 ,Millisecond614
注意,注意