jQuery验证ajax不适用于验证码检查
问题描述:
这是我的代码:
$.validator.addMethod('checkCaptcha', function(value) {
$.ajax({
type: 'POST',
headers: {"cache-control": "no-cache"},
url: baseURI + '/ajax-process/?rand=' + new Date().getTime(),
async: true,
cache: false,
dataType: "json",
data: 'controller=validate_captcha&c_value=' + value,
success: function (jsonData) {
console.log(jsonData.check_result) // It return true.
if (jsonData.check_result) {
return true;
}
reuturn false;
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
reuturn false;
}
});
return false;
}, 'Captcha invalid!');
$('#order_form_wrap').validate({
rules: {
'order_form[captcha]': {
checkCaptcha:true
}
}
});
当我记录jsonData结果时,它返回"true",但验证插件会提示错误消息. 我怎么了有人可以帮助我吗?
When i log jsonData result, it return "true", but validate plugin alert the error message. What is my error? Somebody can help me?
答
您的逻辑结构有问题... ajax()
是异步的,因此函数的最后一行在
It's a problem with your logical construction... ajax()
is asynchronous, so the very last line of your function is returning false
before your ajax()
is complete.
$.ajax({
....
success: function (jsonData) {
....
if (jsonData.check_result) {
return true;
}
reuturn false; // <-- misspelled "return"
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
reuturn false; // <-- misspelled "return"
}
});
return false; // <-- this fires before your ajax
jQuery Validate的开发人员没有尝试解决问题或解决方法,已经解决了这些问题.只需使用内置的remote
方法 ...
Instead of trying to fix or workaround that, the developer of jQuery Validate has already solved the issues. Simply use the built in remote
method...
$('#order_form_wrap').validate({
rules: {
'order_form[captcha]': {
remote: {
type: 'POST',
headers: {"cache-control": "no-cache"},
url: function() {
return baseURI + '/ajax-process/';
},
// async: true, // default
// cache: false, // 'false' only works with HEAD and GET, see docs
// dataType: "json", // default
data: {
rand: function() {
return new Date().getTime();
},
controller: function() {
return 'validate_captcha';
},
c_value: function() {
return value;
}
}
}
}
},
messages: {
'order_form[captcha]': {
remote: 'Captcha invalid!'
}
}
});
See ajax()
docs for available options inside remote
.