jQuery的验证和使用AJAX的自定义规则 [英] jQuery validator and a custom rule that uses AJAX

查看:127
本文介绍了jQuery的验证和使用AJAX的自定义规则的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看了你的关于jQuery的验证器,你勾勒出一个方法来检查用户名对数据库中的一个值回复。

I read your reply regarding the jQuery validator where you outline a method to check a username against a value in a database.

香港专业教育学院试图实施该方法,但无论怎样从PHP文件返回我总是得到一个已经采取了用户名信息。

Ive tried implementing this method but no matter what is returned from the PHP file I always get the message that the username is already taken.

下面是部份效果自定义的方法...

Here is ths custom method...

$.validator.addMethod("uniqueUserName", function(value, element) {
  $.ajax({
      type: "POST",
       url: "php/get_save_status.php",
      data: "checkUsername="+value,
      dataType:"html",
   success: function(msg)
   {
      // if the user exists, it returns a string "true"
      if(msg == "true")
         return false;  // already exists
      return true;      // username is free to use
   }
 })}, "Username is Already Taken");

这里是验证code ...

And here is the validate code...

username: {
    required: true,
    uniqueUserName: true
},

有没有一种特定的方式,我应该从PHP返回的消息。

Is there a specific way i am supposed to return the message from php.

感谢

A

推荐答案

您正在做一个AJAX请求,ERGO:验证已经完成的工作,当你的自定义验证返回true或false

You are doing an AJAX request, ergo: the validation is already finished working when your custom validator returns either true or false.

您需要与工作异步。也看到这个帖子:<一href="http://stackoverflow.com/questions/133310/how-can-i-get-jquery-to-perform-a-synchronous-rather-than-asynchronous-ajax-req">How我可以让jQuery来进行同步,而不是异步,AJAX请求?

You will need to work with async. See also this post: How can I get jQuery to perform a synchronous, rather than asynchronous, AJAX request?

是这样的:

function myValidator() {
   var isSuccess = false;

   $.ajax({ url: "", 
            data: {}, 
            async: false, 
            success: 
                function(msg) { isSuccess = msg === "true" ? true : false }
          });
    return isSuccess;
}

警告:

在jQuery 1.8,采用异步的:假以jqXHR($ .Deferred)是   德precated;您必须使用成功/错误/完整的回调选项   代替jqXHR对象的相应的方法,例如   jqXHR.done()或去precated jqXHR.success()。

As of jQuery 1.8, the use of async: false with jqXHR ($.Deferred) is deprecated; you must use the success/error/complete callback options instead of the corresponding methods of the jqXHR object such as jqXHR.done() or the deprecated jqXHR.success().

这篇关于jQuery的验证和使用AJAX的自定义规则的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆