前一段时间使用jquery.validate时遇到一个棘手的问题. 在使用remote验证规则jquery.validate 不能正常工作. 以下是测试脚本:
$( function (){
$( " #form1 " ).validate({
rules:{
txt1:{
remote:{
url:"http:" // www.cnblogs.com/a_bu/admin/%22Handler2.ashx
,type: " post "
,data:{ " key " : " ss " }
,error: function (a,s,d){
alert(s + " " + d);
}
}
}
}
,messages:{
txt1:{
remote: " 位空 "
}
}
})
})
< / script>
猜测可能是兼容问题,于是分别用jquery 1.44版与 jquery 1.51版做测试,其结果基本一致,分别提示:"error undeined"与"parsererror jQuery15109425226654151397_1299202557390 was not called".
使用fiddler检测,服务端响应结果正常.因此排除了服务端因素。所以问题可能出现在jquery.validate插件本身上。之后在google中搜到一种解决方案.https://github.com/bigfix/jquery-validation/commit/9aa53f9241224ba349f9fe1b2c801be0f431b63b#undefined ,使用该替代方案后remote验证工作正常.
从1087行截止1100行源码:
var pendingRequests = {};
$.ajax = function (settings) {
// create settings for compatibility with ajaxSetup
settings = $.extend(settings, $.extend({}, $.ajaxSettings, settings));
var port = settings.port;
if (settings.mode == " abort " ) {
if ( pendingRequests[port] ) {
pendingRequests[port].abort();
}
return (pendingRequests[port] = ajax.apply( this , arguments));
}
return ajax.apply( this , arguments);
};
替换为:
if ($.ajaxPrefilter) {
$.ajaxPrefilter( function (settings, original, jqXHR) {
var port = settings.port;
if (settings.mode == " abort " ) {
if ( pendingRequests[port] ) {
pendingRequests[port].abort();
}
pendingRequests[port] = jqXHR;
}
});
} else {
var ajax = $.ajax;
$.ajax = function (settings) {
// create settings for compatibility with ajaxSetup
settings = $.extend(settings, $.extend({}, $.ajaxSettings, settings));
var port = settings.port;
if (settings.mode == " abort " ) {
if ( pendingRequests[port] ) {
pendingRequests[port].abort();
}
return (pendingRequests[port] = ajax.apply( this , arguments));
}
return ajax.apply( this , arguments);
};
}
remote验证测试例子:
http://files.cnblogs.com/a_bu/validate.test.zip
另一个修复方法:http://www.cnblogs.com/a_bu/archive/2011/03/06/1972202.html