AJAX不是即时的

时间:2014-12-17 10:58:37

标签: php ajax

我的代码尝试使用AJAX实现关键字搜索框以在写入时获得实时结果,但我不能这样做。但是,当我去键盘输入时,它会搜索。我的问题是在写作时不必按ENTER键。

示例我想实现:http://expresso.sapo.pt/ranking-das-escolas-2013=f840093

的index.html:

<!DOCTYPE html>
<html>
<head>
<title> Escolha de molecula</title>

<script>
    function showUser(str) {
        if (str=="") {
            document.getElementById("ajax").innerHTML="";
            return;
        } 

        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) {
                document.getElementById("ajax").innerHTML=xmlhttp.responseText;
            }
        }

        var txq=document.getElementById("textquery").value; 
        xmlhttp.open("POST","output.php",true); 
        xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");            
        xmlhttp.send("textquery=" + txq); 
    }
</script>

</head>


<body>
    <h1 style="text-align:center;font-size: 60px"> 
        Search for molecule in our database 
    </h1>
    <hr>
        <p style="color:blue">
        <q>
            I have lived much of my life among molecules. They are good company.
        </q>
        George Wald
        </p>
    <hr>

    <p style="font-family:verdana">
        just write something in the search bar and it will retrieve it    <br>
        More information at: <a href="http://xldb.fc.ul.pt/" target="_blank">http://xldb.fc.ul.pt/</a>        
    </p>


    search: <input type="text"  id="textquery" onchange="showUser()" ><br> 

    </form>

    <br>

    <div id="ajax"><b>search results will be shown here</b></div> 
</body>
</html>

output.php:

<?php

$con=mysqli_connect("127.0.0.1","","","ulchemd");
    // Check connection
if (mysqli_connect_errno()) {
    echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

$pesquisa =mysqli_real_escape_string($con, $_POST['textquery']);
$resposta = mysqli_query($con,"SELECT * from target WHERE molecule.target_text like '%$pesquisa%' ");

echo " <b> Search results:";




echo "<table border='5'>
<tr>
<th>ID</th>
<th>target_type</th>
<th>name</th>
<th>text</th>
</tr>";


while($row = mysqli_fetch_array($resposta)) { 
//este while vai buscar cada linha da tabela num ciclo como um cursor
  echo "<tr>";
  echo "<td>" . $row['tid'] . "</td>";
  echo "<td>" . $row['target_type'] . "</td>";
  echo "<td>" . $row['name'] . "</td>";
  echo "<td>" . $row['target_text'] . "</td>";
  echo "</tr>";
}

echo "</table>";

mysqli_close($con);
?>

非常感谢:)

1 个答案:

答案 0 :(得分:3)

更改

onchange="showUser()"

onkeyup="showUser()"
当元素失焦时会发生

onchange事件,即模糊。

这就是它不能直播的原因。

当用户按下文本框中的任何键时,

onkeyup将触发,这是必需的。