0

我正在尝试根据数据库值创建一个特殊的邮政编码验证。因此,我正在通过 ajax 检查值:

jQuery.validator.addMethod("validate_country_from", function(value, element) 
{
   $.ajax({
      type: "POST",
      url: "ajax.php",
      data: "action=validate_countryzip&direction=1&zip=" + 
         escape(document.getElementById("zip_from").value) + "&country=" + 
         escape(document.getElementById("country_from").value),
      async: false
   }).done(function(msg)
   {
      if(msg == "true")
      {
         return true;
      }
      else
      {
         return false;
      }
   });
}, addressError);

我通过这些规则在规则中分配功能:

zip_from: {
   required: true,
   validate_country_from: true
},
country_from: {
   required: true,
   validate_country_from: true
},

ajax 请求工作正常,它是同步完成的,返回的值也是正确的,但我的验证仍然告诉我这两个字段有错误。

我希望有人能帮帮忙...

4

2 回答 2

1

我认为你在那里混合了你的 jQuery AJAX 方法。以前见过done()用过,以后get()没用过ajax()。尝试

jQuery.validator.addMethod("validate_country_from", function(value, element) 
{
   $.ajax({
      type: "POST",
      url: "ajax.php",
      data: "action=validate_countryzip&direction=1&zip=" + 
         escape(document.getElementById("zip_from").value) + "&country=" + 
         escape(document.getElementById("country_from").value),
      async: false,
      success: function(msg){
          if(msg == "true")
          {
              return true;
          }
          else
          {
              return false;
          }
      },
      error: function(x, s, e){
          return false;
      }
   });
}, addressError);
于 2012-04-06T20:07:14.270 回答
0

谢谢你的回答,但我找到了原因:我的“完成”函数正在向 ajax 请求操作返回一个值,而不是向验证方法返回一个值(匿名代表很棒,但有时真的很混乱)。

正确的版本是这样的:

jQuery.validator.addMethod("validate_country_from", function(value, element) 
{
   var test = $.ajax({
      type: "POST",
      url: "ajax.php",
      data: "action=validate_countryzip&direction=1&zip=" + 
         escape(document.getElementById("zip_from").value) + "&country=" + 
         escape(document.getElementById("country_from").value),
      async: false
   }).done(function(msg)
   {
   });

   if(test.responseText == "true")
   {
      return true;
   }
   else
   {
      return false;
   }
}, addressError);

但是,这不是最终解决方案,因为它没有捕获任何错误等等。

于 2012-04-07T20:39:53.247 回答