jQuery远程验证 [英] jQuery Remote validation
问题描述
我对jQuery远程验证有问题.我正在检查电子邮件是否已注册,远程验证是否有效,但它仅显示值-true或false,因此我无法提交该表单.
I have a problem with jQuery remote validation. I am checking if email is registered, remote validation works, but it display only values - true or false and I cant submit the form than.
jQuery代码:
$("#form").validate({
rules: {
email: {
required: true,
email: true,
remote: "check-email.php"
}
}
});
check-mail.php代码:
check-mail.php code :
$email = trim(strtolower($_REQUEST['email']));
$checkemail = mysql_query("SELECT * FROM users WHERE email = '".$email."'");
if(mysql_num_rows($checkemail) == 1)
{
$valid = 'false';
}
else
{
$valid = 'true';
} //end of $checkemail if statemant
echo json_encode($valid);
推荐答案
$checkemail = mysql_query("SELECT * FROM users WHERE email = '".$email."'");
永远不要永远 永远执行此操作.这是寻求麻烦:SQL注入,随机错误(单引号在电子邮件地址中有效,BTW).
Never ever ever ever do this. This is asking for trouble: SQL injection, random errors (the single quote is valid in email addresses, BTW).
有参数化查询,请使用它们.只是多了几行代码,但它是一个安全的漏洞,一个谷仓门之类的安全漏洞与安全的数据库交互之间的区别.
There are parameterized queries, use them. It's only a few lines more of code, but it is the difference between a security flaw as wide as a barn door and a safe database interaction.
if(mysql_num_rows($checkemail) == 1)
{
$valid = 'false';
}
else
{
$valid = 'true';
}
是非常冗长的说法
$valid = mysql_num_rows($checkemail) == 1;
根据文档,远程验证的响应是JSON编码的 boolean ,而不是JSON编码的 string .
According to the docs, the response of remote validation is a JSON-encoded boolean, not a JSON-encoded string.
您有"true"
或"false"
,它们将通过json_encode()
变为"\"true\""
或"\"false\""
,这是错误的.实际的true
或false
将变为"true"
或"false"
,这是正确的.
You have "true"
or "false"
, which will become "\"true\""
or "\"false\""
through json_encode()
, which is wrong. Actual true
or false
will become "true"
or "false"
, which is correct.
将响应内容类型设置为JSON也可能是一个好主意:
Setting the response content type to JSON might also be a good idea:
header('Content-type: application/json');
这篇关于jQuery远程验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!