来自jQuery Validate远程的错误响应无法正常工作

bre*_*ine 5 jquery jquery-validate

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

$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"
        }
    });
});
Run Code Online (Sandbox Code Playgroud)

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

从注释掉的行中可以看出,我一直试图通过猜测和检查来弄清楚我到底做错了什么,假设我以某种方式以错误的格式返回错误字符串,但是我没有成功.

Edit3: 我能够让后端响应发生变化.PHP现在发送JSON编码true/ false,但无济于事.我们尝试通过以下方式发送后端响应,但无论我们做什么,插件似乎都没有捕获它:

json_encode( false )
json_encode( '["false"]' )
json_encode( "false" )
json_encode( ["false"] )
"false"
false
NULL
""
0
Run Code Online (Sandbox Code Playgroud)

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

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

请注意,此问题的答案可能与此问题有关.

这是修改后的代码:

$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."
   }
});
Run Code Online (Sandbox Code Playgroud)

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

bre*_*ine 7

好吧,最后随机弄清楚了.该success回调显然破坏了一切.我所要做的就是删除它:

success: function(data){
    console.log(data);
}
Run Code Online (Sandbox Code Playgroud)

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

"true"
Run Code Online (Sandbox Code Playgroud)

"false"
Run Code Online (Sandbox Code Playgroud)

我无法解释这一点,但我希望有人更新文档!我注意到使用complete不会破坏它的方式success.

  • 我也让这个工作,只需让我的PHP脚本`echo"true";`或`echo"false"`. (3认同)