javascript 在 jquery 验证中使用远程方法的问题
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16213712/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Issue using remote method in jquery validation
提问by GVillani82
I'm following thisarticle in order to validate my form
我正在关注这篇文章以验证我的表单
My problem is when I have to use the remote
method, e.g. remote: "check-username.php"
我的问题是当我必须使用该remote
方法时,例如remote: "check-username.php"
Since the documentationfor remote method is not so clear for me, I would know:
由于远程方法的文档对我来说不是很清楚,我会知道:
How I need to structure my json output in php script?
我需要如何在 php 脚本中构建我的 json 输出?
采纳答案by gradosevic
You don't need JSON. You can put any text. For example you can
你不需要 JSON。您可以放置任何文本。例如你可以
echo "success";
for passed validation, and enter validation message like:
对于通过的验证,并输入验证消息,如:
echo "Username already exists.";
for failed validation.
对于失败的验证。
In your callback do something like this:
在你的回调中做这样的事情:
remote: {
url: "check-username.php" ,
type: "post" ,
data: {
username: function() {
return $("#username").val();
},
complete: function(data){
if( data.responseText != "success" ) {
alert(data.responseText);
//handle failed validation
}
}
}
回答by manta
To use the default method for remote
, the remote page must respond with a string value of "true"
or "false"
.
要使用 的默认方法remote
,远程页面必须以"true"
或的字符串值响应"false"
。
Valid(success) Must be:
有效(成功)必须是:
echo "true";
Invalid(failure):
无效(失败):
echo "false"; // this can be any false. eg: 0 , "" , NULL.
The response will be evaluated as JSON.
响应将被评估为 JSON。
To apply an error message, other than the default for a remote response of invalid ("false"), add the input name to the validator options messages
object like so.
要应用错误消息,而不是远程响应的默认值无效(“false”),请将输入名称添加到验证器选项messages
对象中,如下所示。
rules:{
username:{
remote: "check-username.php"
}
},
messages:{
username:{
remote: jQuery.format('{0} is already in use, please choose a different name')
}
}