Javascript jquery ajax延迟对象不返回值
我有这个密码Javascript jquery ajax延迟对象不返回值,javascript,jquery,Javascript,Jquery,我有这个密码 if (!checkIfCustomerIsValid(event)) { event.preventDefault(); return false; } else { AddCustomer(); } function checkIfCustomerIsValid(event) { if ($('#txtCName').val() == '') { alert('Please enter a valid va
if (!checkIfCustomerIsValid(event)) {
event.preventDefault();
return false;
}
else {
AddCustomer();
}
function checkIfCustomerIsValid(event) {
if ($('#txtCName').val() == '') {
alert('Please enter a valid value for customer name!');
return false;
}
if ($('#txtCAddress').val() == '') {
alert('Please enter a valid value for customer address!');
return false;
}
}
在那之前,它还不错,但我加了一张新支票,它什么也不退
function checkIfCustomerIsValid(event) {
// code that was already there, the name and address check
var _mobNo;
if ($('#txtMobile').val() == '') return false;
var _unq = $.ajax({
url: '../Autocomplete.asmx/IsMobileUnique',
type: 'GET',
contentType: 'application/json; charset=utf8',
dataType: 'JSON',
data: "mobileNo='" + $('#txtMobile').val() + "'",
async: false,
timeout: 2000,
success: function (res) { if (res.d) return false; else return true; },
error: function (res) { alert('some error occurred when checking mobile no'); }
}),chained = _unq.then(function (data) { if (data.d == false) { alert('mobile no already exists!'); $('#txtMobile').focus(); return false; } return true; });
}
如果手机号码不唯一,则警报会显示手机号码不唯一,但当手机号码唯一时,代码不会进入
AddCustomer
(在其他部分)???这不是真的吗?为什么不进入AddCustomer
?新测试中,checkIfCustomerIsValid
是异步的。它没有办法直接返回远程呼叫的结果,即使是延迟的
这里最简单的方法是将回调传递给
checkIfCustomerIsValid
函数,或者从函数返回承诺。当您混合使用同步和异步测试时,最好将回调传递给checkIfCustomerIsValid
如果您是正确的,那么checkIfCustomerIsValid不会返回true。这是因为您试图从匿名函数(即ajax请求后的回调)返回true。当您从
chained = _unq.then(function (data) { if (data.d == false) { alert('mobile no already exists!'); $('#txtMobile').focus(); return false; } return true; });
您仅从该匿名函数返回,而不是从checkIfCustomerIsValid返回。解决这个问题并不完全是直截了当的,而是由异步调用的性质造成的问题。最常见的解决方案是向异步调用传递回调。这是一把实现这一点的小提琴
Ajax是异步的,不会阻塞,因此返回值很可能未定义。您可以将代码修改为以下内容:
success: function (res) { if (res.d) callRoutineToAddCustomer(); },
可能重复的可能重复我已经设置了'async:false',那么它怎么仍然是异步的呢?永远不要使用
async
:它会阻塞UI。我知道,但我只是指出,你说我已经设置了'async:false',所以现在不应该是异步的?不赞成将async与deferred一起使用。不管它是否阻塞,您仍然在使用匿名函数,并且在匿名函数中返回只会从该匿名函数中返回,而不是checkIfCustomerIsValid。这是因为像q.unq.then中的匿名函数这样的回调是在函数之外的其他地方运行的,它们能够向原始方法返回值在逻辑上是没有意义的。