【问题标题】:Error response from jQuery Validate remote isn't working来自 jQuery Validate 远程的错误响应不起作用
【发布时间】:2013-10-23 20:24:30
【问题描述】:

我正在使用jQuery Validationremote 方法来检查系统中是否已经存在用户名。如果用户存在,脚本does_user_exist.php 返回1

$registration.find(".username").each(function() {
    var $this = $(this);
    $this.rules('add', {
        remote: {
            url: "does_user_exist.php",
            type: "post",
            dataType: "json",
            data: {uname: function(){ return $this.val(); } },
            async: false,
            success: function (data) { //returns 1 if user exists
                if (data) {
                   console.log("false!");
                   return "Sorry, that user already exists." //doesn't work
                   //return false;        //doesn't work
                   //return data;         //doesn't work
                   //return {"string"};   //doesn't work
                   //return {0: "string"};//doesn't work
                } else {
                   console.log("true!");
                   return true;
                }
            }
        },
        messages: {
            remote: jQuery.format("{0}") //doesn't work
            // remote: "Simple string doesn't work here either"
        }
    });
});

我的问题是永远不会显示错误消息。我可以从我的console.log 输出中看到,当用户存在时,它会正确记录false!,但错误消息永远不会出现。

正如您从注释掉的行中看到的那样,我一直试图通过猜测和检查来找出我到底做错了什么,假设我以某种方式返回了错误的错误字符串格式,但我没有成功。

编辑3: 我能够更改后端响应。 PHP 现在发送 JSON 编码的true/false,但无济于事。我们尝试通过以下方式发送后端响应,但无论我们做什么,插件似乎都无法捕捉到它:

json_encode( false )
json_encode( '["false"]' )
json_encode( "false" )
json_encode( ["false"] )
"false"
false
NULL
""
0

据我所知,根据文档,其中一个应该有效:

响应被评估为 JSON 并且对于有效元素必须为 true, 并且对于无效元素可以是任何 false、undefined 或 null,使用 默认消息;

注意,这个问题的答案可能与this issue有关。

这是修改后的代码:

$registration.find(".username").each(function() {
    var $this = $(this);
    remote: {
        url:  "does_user_exist.php",
        type: "post",
        data: {entityExistence: function(){return $this.val();} },
        success: function(data){ console.log(data); }
    },
    messages: {
        remote: "Sorry, that username is not available."
   }
});

PHP 脚本始终正确返回 truefalse。根据文档,除了true 之外的任何内容都应该触发错误消息。但是错误信息没有出现。我知道错误消息正在工作,因为还有其他检查工作正常(例如,rangelength,为了清楚起见,从此处的粘贴代码中删除)。

【问题讨论】:

  • 您没有阅读远程方法的文档?它清楚地解释了您的服务器代码必须返回的内容。
  • @Sparky:顺便说一句,是的,我确实阅读了文档,特别是其中的this part响应被评估为 JSON,并且对于有效元素必须为 true,并且可以是任何对于无效元素,使用默认消息为 false、undefined 或 null;或字符串,例如。 “该名称已被占用,请尝试 peter123”以显示为错误消息。
  • 还引用:"必须为true 才能获得有效元素" ~ 当用户不存在时,它是否返回true?您的1 是被解释为字符串还是true?我们已经知道1 不是“false, undefined or null”
  • 是的,这就是文档所说的。 “响应”是指来自您的服务器脚本的响应:响应被评估为 JSON,对于有效元素必须true,并且可以对于无效元素是任何 false、未定义或 null..."
  • 您不需要特别通过 JavaScript 来 return 任何东西。文档谈论从您的服务器返回的内容。

标签: jquery jquery-validate


【解决方案1】:

返回字符串不会自动显示它。如果要显示它,则需要执行以下操作:

$('#myDiv').html('<p class="error">Sorry, that user already exists.</p>');

【讨论】:

  • 感谢您的提示,但我需要验证器来处理错误,而不是手动处理。我正在将它与 tooltipster 集成,但除此之外,使用自动处理错误消息然后绕过该功能手动执行它的插件是没有意义的。如果我想手动完成,我一开始就不会使用该插件。
【解决方案2】:

documentation for the remote method 声明:

服务器端响应必须是 JSON 字符串,对于有效元素必须是 "true",对于无效元素可以是 "false"undefinednull,使用默认错误消息。如果服务器端响应是一个字符串,例如。 "That name is already taken, try peter123 instead",此字符串将显示为自定义错误消息代替默认值。


引用 OP:

“如果用户存在,脚本does_user_exist.php返回1。”

这可能与您想要的相反。因为1 可能会被解释为true,它告诉插件它“通过”了验证。根据文档,如果用户存在并且您想要触发错误消息,则响应必须是 falseundefinednull 或字符串(消息)。

【讨论】:

【解决方案3】:

好的,终于想通了,随机的。 success 回调显然毁了一切。我所要做的就是删除这个:

success: function(data){
    console.log(data);
}

我这样做后,使用简单的字符串响应,一切都按预期完美运行:

"true"

"false"

我无法解释这一点,但我希望有人更新文档!我注意到使用complete 不会像success 那样破坏它。

【讨论】:

  • 我也得到了这个工作,只需使用我的 PHP 脚本 echo "true";echo "false"
  • 文档说:“服务器端响应必须是 JSON 字符串,必须是 true...”但最好只使用 echo 'true';echo 'false'; 并忘记 JSON 部分跨度>
【解决方案4】:

不幸的是,上面的答案有点神秘。

为了让它工作,你需要跟随 JS。

$('#register-form').validate({
    rules: {
        'first-name': "required",
        'surname': "required",
        'email': {
            required: true,
            email: true,
            remote: {
                url: 'ajax/users/emailInUse',
                type: 'post',
                data: {
                    email: function() {
                        return $('input[name=email]').val();
                    }
                }
            }
        },
        'username': "required",
        'password': "required",
        'confirm-password': {
            equalTo: "input[name=password]"
        }
    },
    messages: {
        'first-name': "Please enter your first name",
        'surname': "Please enter your surname",
        'email': {
            required: "Please enter your email address",
            email: "Please enter a valid email e.g. yoda@jedi.com"
        },
        'username': "Please enter a username",
        'password': "Please enter a password",
        'confirm-password': "Passwords do not match"
    }
});

您的后端代码应该运行检查电子邮件是否有效,并将结果作为 json 字符串中的消息返回。例如

[
    " is already in use..."
]

示例后端代码:

public function emailInUseAction()
{

    $this->setJsonResponse();

    if($this->request->isAjax())
    {

        $email = $this->request->getPost('email');

        $emailInUse = Users::emailInUse($email);

        $message = false;

        if($emailInUse)
        {

            $message = $email . ' is already in use...';

        }

        return array(
            $message
        );

    }

}

希望这对遇到问题的人有所帮助!

【讨论】:

    猜你喜欢
    • 2015-10-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-04
    • 2019-07-24
    • 2013-03-14
    • 1970-01-01
    相关资源
    最近更新 更多