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


How to implement an AJAX op while creating a search bar?

我试图使用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");
    }
}
}

首先,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>';
?>