nik*_*iko 1 javascript php forms validation ajax
我正在尝试在用户提交表单时向服务器发送AJAX请求,我这样做是为了检查该电子邮件是否已被其他人使用或是否是新的.
这是我的javascript AJAX函数
function check_entireform()
{
var new_email = document.getElementById('jemail').value;
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
var y =xmlhttp.responseText;
if(y=="user with that email is already registered")
return false;
}
}
var x ="user_exists.php?email="+ new_email;
xmlhttp.open("GET",x,true);
xmlhttp.send();
}
Run Code Online (Sandbox Code Playgroud)
这是我的html输入标记
<form method="post" action="./new.php" onsubmit="return check_entireform()">
<input type="text" name="email" id="jemail"/>
</form>
Run Code Online (Sandbox Code Playgroud)
这是我的user_exists.php文件
<?php
$email=$_GET["email"];
if(mysql_query("SELECT email FROM user_info WHERE email='$email'"))
echo "user with that email is already registered";
else
echo"user got a new email";
?>
Run Code Online (Sandbox Code Playgroud)
当用户提交表单时,我想通过AJAX将用户电子邮件发送到user_exists.php文件,然后查看该电子邮件是否已被某人使用,并回显一些已经在使用的信息.
我不知道哪里出错了.我一直在提交相同的电子邮件,但它没有回应,也没有阻止我提交表格.
如果有更好的解决方案可以找出某人是否已经使用过电子邮件会很棒.谢谢
这意味着回调函数(您定义的函数onreadystatechange)将仅在服务器响应时运行.另一方面,您的submit处理程序check_entireform将比此更早地返回.它返回undefined,其结果为false,因此您的表单未提交.
始终阻止提交并将参考传递给表单:
<form method="post" action="./new.php" onsubmit="check_entireform(this); return false;">
Run Code Online (Sandbox Code Playgroud)
接受参考:
function check_entireform(theform) {
Run Code Online (Sandbox Code Playgroud)
然后在需要时提交表格:
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
var y =xmlhttp.responseText;
if(y != "user with that email is already registered")
theform.submit();
}
Run Code Online (Sandbox Code Playgroud)
jsFiddle演示 - 没有AJAX,只有模拟
提示:您应该只返回0或1,而不是从PHP返回长字符串.您应该将AJAX查询视为是 - 在这种情况下没有问题(可以使用此电子邮件吗?).1表示是,而0表示否.
因此,您可以将代码更改为:
var canBeUsed =xmlhttp.responseText;
if (canBeUsed) theform.submit();
Run Code Online (Sandbox Code Playgroud)
它将变得更容易阅读和维护.
在这一行:
var x ="user_exists.php?email="+ new_email;
Run Code Online (Sandbox Code Playgroud)
您应该对new_email变量进行URL编码,因为某些字符(如&)在查询字符串中具有特殊含义并且应进行编码.您可以使用encodeURIComponent()函数执行此操作:
var x ="user_exists.php?email="+ encodeURIComponent(new_email);
Run Code Online (Sandbox Code Playgroud)
始终清理(并验证)来自外部的任何数据.在目前的形式中,您的代码容易受到SQL注入攻击,这是一个巨大的问题.
在将数据插入查询之前,您应该使用mysql_real_escape_string()它(或者更好的是,将PDO用于数据库的东西).
$email = mysql_real_escape_string($_GET["email"]);
if(mysql_query("SELECT email FROM user_info WHERE email='$email'"))
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
255 次 |
| 最近记录: |