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

查看:26
本文介绍了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.

这是自定义方法...

$.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");

这是验证码...

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

是否有一种特定的方式我应该从 php 返回消息.

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

谢谢

A

推荐答案

您正在执行 AJAX 请求,因此:当您的自定义验证器返回 true 或 false 时,验证已经完成.

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

您将需要使用 async.另见这篇文章:如何让 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 开始,使用 async: false 和 jqXHR ($.Deferred) 是已弃用;您必须使用成功/错误/完成回调选项而不是 jqXHR 对象的相应方法如jqXHR.done() 或已弃用的 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天全站免登陆