使用PHP和AJAX在服务器端验证时遇到问题

时间:2012-08-27 17:23:01

标签: php jquery ajax

我只想在输入电子邮件后,它会自动显示是否可以使用电子邮件(不存在于数据库中)或不存在(存在于数据库中)。当我输入时,没有显示的输出。截至目前,我有这个代码。我应该如何解决这个问题

这是我的主页代码

<!DOCTYPE HTML>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Jquery-ajax Practice</title>
</head>

<body>
<section>
    <form>
        <label for="text_email">E-mail:</label>
        <input id="text_email" type="email" >

        <script type="text/javascript" charset="utf-8" src="//ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js">
            $(document).ready(function(){
                $('#text_email').keyup(function(){
                    email($(this).val());
                });
            });
            function email(str){
                $.post('checkmail.php',{ email: str},
                function(data){
                    $('#check_email').html(data.returnValue);
                }, 'json');
            }
        </script>

        <label for="text_email" id="check_email"></label>   
    </form>
</section>
</body>
</html>

这是我的PHP代码

<?php
if(isset($_POST['email']))
{
    try 
    {
        $pdo=new PDO('mysql:host=localhost;dbname=class;charset=utf-8', 'root');
    }
    catch(PDOException $e)
    {
        echo 'Failed: '.$e->getMessage();
    }

    $stmt=$pdo->prepare('SELECT email FROM class where email=:email LIMIT 1');
    $stmt->execute(array(':email'=>$_POST['email']));
    if($stmt->rowCount()>0)
    {
        $check='E-mail cannot be use.';
    }
    else
    {
        $check='E-mail can be use.';
    }

    echo json_encode(array('returnValue'=>$check));
}
?>

1 个答案:

答案 0 :(得分:1)

我可以看到的一个问题是你处理数据库错误。

您应该将所有PDO操作包装在try - catch块中(而不仅仅是连接部分),当您发现错误时,您需要将其包装在json_encode中最后的陈述也不仅仅是回应它,因为这会使客户端收到的json无效。

我不知道您的数据库设置,但您没有提供密码,我认为您的连接字符串应该有charset=utf8