【发布时间】:2013-10-23 20:24:30
【问题描述】:
我正在使用jQuery Validation 的remote 方法来检查系统中是否已经存在用户名。如果用户存在,脚本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 脚本始终正确返回 true 或 false。根据文档,除了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任何东西。文档仅谈论从您的服务器返回的内容。