如何在创建搜索栏时实现AJAX操作?

时间:2014-07-27 14:30:14

标签: php jquery ajax

我试图使用AJAX创建搜索栏,搜索数据库中的用户。 AJAX工作得很好;当没有输入任何内容或没有找到用户时,它会显示正确的消息。问题是,即使找到用户,它也不会显示用户。这是PHP文件:

<?php
    header('Content-Type: text/xml');
    echo '<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>';
    require_once("includes/connection.php");
    echo '<response>';
    $user=$_GET['user'];

    if($user==""){
           echo "type the username";
    }
    else{   
           $query="SELECT email_id FROM users WHERE email_id={$user}";
           $user_result = mysql_query($query,$connection);

           if($user_result){
                echo "yeah {$user} exists";
           }
           else{
                echo "no such user as {$user} exists";
           }
    }

    echo '</response>';
?>

我没有包含创建xmlHTTP对象的函数,但这是JavaScript代码的其余部分:

function start()
{

if(xmlHttp){
try{
    if(xmlHttp.readyState==0 || xmlHttp.readyState==4)
    {
        user= encodeURIComponent(document.getElementById("user_input").value);
        xmlHttp.open("GET","search.php?user="+user,true);
        xmlHttp.onreadystatechange = mainFunctionHandler;
        xmlHttp.send(null);
    }else{
        setTimeout('start()',1000);
    }
}catch(e){
    alert(e.toString());
        }
}
}

function mainFunctionHandler()
{
if(xmlHttp.readyState==4){
    if(xmlHttp.status==200){
        xmlResponse = xmlHttp.responseXML;
        xmlDocumentElement = xmlResponse.documentElement;
        message = xmlDocumentElement.firstChild.data;
        document.getElementById("divD").innerHTML=message;
        setTimeout('start()',1000);
    }else{
        alert("something went wrong");
    }
}
}

1 个答案:

答案 0 :(得分:1)

首先,不推荐使用mysql_ *函数,不应该使用。在此处阅读更多内容:https://stackoverflow.com/a/12860046/3877639

但是,你的PHP应该是这种情况(检查$result有多少行。如果有0次点击/行,它将返回true:

<?php
    header('Content-Type: text/xml');
    echo '<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>';
    require_once("includes/connection.php");
    echo '<response>';
    $user=$_GET['user'];

    if($user==""){
           echo "type the username";
    }
    else{   
           $query="SELECT email_id FROM users WHERE email_id={$user}";
           $user_result = mysql_query($query,$connection);

           if(mysql_num_rows($user_result) > 0){
                echo "yeah {$user} exists";
           }
           else{
                echo "no such user as {$user} exists";
           }
    }

    echo '</response>';
?>