在php中使用AJAX检查电子邮件可用性

时间:2014-09-08 16:07:09

标签: javascript php html mysql ajax

我需要检查此任务的电子邮件可用性。当我输入任何电子邮件地址后,我按Tab键后应该检查数据库并返回该电子邮件是否已经存在。 但是这个例程给出了在控制台中检查时我所期望的精确输出。但错误信息没有写在我的html页面上。谁能帮我?提前致谢。

HTML编码

<div class="txtinputcomp">
   <input name="frmVisitorEmail" id="frmVisitorEmail" onblur="checkEmail(this.value);" class="emailbox" required="required" value="<?php echo $_POST['frmVisitorEmail']; ?>" placeholder="Visitor Email" type="email" />   
    </div>
<div class="emptytxtcomp">
     <span id="errorEmail" class="errorStyle"></span>
 </div>

FindEmail.php

<?php
    include("includes/config.php"); 
    $strEmail = $_GET["email"];
    $strData = doCheckEmail($strEmail);
    if($strData!=0) {
        echo "<script type='text/javascript'>
            document.getElementById('errorEmail').innerHTML = 'Email address are already exist!';
            return false;
        </script>";

    } else {
        echo '<script type="text/javascript"> 
            document.getElementById("errorEmail").innerHTML = "";
        </script>';
    }
?>

AJAX脚本

function checkEmail(str)
{
    var xmlhttp;
    if (str.length==0) {
        document.getElementById("frmVisitorEmail").innerHTML="";
        return;
    }
    if (window.XMLHttpRequest) {
        xmlhttp=new XMLHttpRequest();
    } else {
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.onreadystatechange=function() {
        if (xmlhttp.readyState == 4 && xmlhttp.status==200) {
            document.getElementById("frmVisitorEmail").innerHTML=xmlhttp.responseText;
        }
    }
    xmlhttp.open("GET","findEmail.php?email="+str,true);
    xmlhttp.send(null);
}

功能

function doCheckEmail($strIdent)
    {
        $strSelectsSql = "Select count(*) as TotalCnt from tbl_visitor Where visitor_email='".$strIdent."' ";
        $strSelectsResult = SelectQry($strSelectsSql);
        return $strSelectsResult[0][0];
    }


function SelectQry($Qry) {
        $result = mysql_query($Qry) or die ("QUERY Error:".$Qry."<br>".mysql_error());      
        $numrows = mysql_num_rows($result); 
        if ($numrows == 0) {            
            return;
        } else {
           $row = array(); 
           $record = array();
           while ($row = mysql_fetch_array($result)) { 
                $record[] = $row; 
           }        
        }   
        return MakeStripSlashes($record);
    }

1 个答案:

答案 0 :(得分:2)

此行不会运行PHP回显的脚本:

document.getElementById("frmVisitorEmail").innerHTML=xmlhttp.responseText;

要执行动态添加的Javascript,您必须使用createElement来创建script元素。

相反,我建议PHP只返回错误消息,而不是脚本块。所以它应该是:

if($strData!=0) {
    echo "Email address are already exist!";
} else {
    echo "";
}

然后Javascript将是:

xmlhttp.onreadystatechange=function() {
    if (xmlhttp.readyState == 4 && xmlhttp.status==200) {
        document.getElementById("errorEmail").innerHTML=xmlhttp.responseText;
    }
}