如何在php中使用ajax搜索关键字


How to search the keyword using ajax in php

不显示任何从php到ajax的数据。如有任何帮助,我们将不胜感激。

HTML:

 Search Box:<input type="text" name="search" id="search">
 <div id="search1"></div>

AJAX:

        $("#search").keyup(function(){
        var search=$(this).val();
                 $.ajax({  //GR ID Generation
                  method: "GET",
                  url: "search_rep.php?invo="+search,
                })
                  .done(function( msg ) {
        $("#search").html(msg); 
        $("#search1").val();      
        }); 

PHP:

    $in  = mysql_real_escape_string($_GET['invo']);
    $msg = '';
    if(strlen($in) > 0 && strlen($in) < 20){
      $row = mysql_query("SELECT Bot_Name
                        FROM bot_info 
                        WHERE Bot_Name 
                        LIKE '%$in%'and  Bot_Type='Printed'",$con );
      while($result = mysql_fetch_array($row)){
        $msg .= $result['Bot_Name'] . "<br />";
      }
    }

一旦你键入一个单词,输出应该显示为谷歌搜索引擎自动显示所有与该单词有关的句子。

您似乎没有在PHP中将任何数据回显到页面上。考虑尝试

$in  = mysql_real_escape_string($_GET['invo']);
$msg = '';
if(strlen($in) > 0 && strlen($in) < 20){
  $row = mysql_query("SELECT Bot_Name
                    FROM bot_info 
                    WHERE Bot_Name 
                    LIKE '%$in%'and  Bot_Type='Printed'",$con );
  while($result = mysql_fetch_array($row)){
    $msg .= $result['Bot_Name'] . "<br />";
  }
}
echo $msg;

您可能还想在PHP中使用MySQLi,而不是即将贬值的MySQL。

如果这不起作用,可能是您的数据库或代码的其他区域出现问题,请告诉我。

javascript

<script>
function showHint(str) {
     if (str.length == 0) {
         document.getElementById("txtHint").innerHTML = "";
         return;
     } else {
         var xmlhttp = new XMLHttpRequest();
         xmlhttp.onreadystatechange = function() {
             if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
                 document.getElementById("txtHint").innerHTML = xmlhttp.responseText;
             }
         }
         xmlhttp.open("GET", "cities.php?invo="+str, true);
         xmlhttp.send();
     }
}
</script>

HTML

<p><b>Start typing a name in the input field below:</b></p>
<form>
First name: <input type="text" onkeyup="showHint(this.value)">
</form>
<p>Suggestions: <span id="txtHint"></span></p>

PHP/Ajax-->cities.PHP

$query=mysql_query("select name from cities", $con);
while($row = mysql_fetch_array($query)){
$a[]=$row['name'];
}
$q = $_REQUEST["invo"];
$hint = "";
if ($q !== "") {
    $q = strtolower($q);
    $len=strlen($q);
    foreach($a as $name) {
        if (stristr($q, substr($name, 0, $len))) {
            if ($hint === "") {
                $hint = $name;
            } else {
                $hint .= ", $name";
            }
        }
    }
}
echo $hint === "" ? "no suggestion" : $hint;