在php代码中触发AJAX onkeyup事件

时间:2013-12-06 03:12:44

标签: javascript php ajax search-engine

我是AJAX脚本和javascript的新手。当用户在搜索框中键入第一个字母时,我正在使用AJAX获取搜索建议。但在输入AJAX和javascript代码后,我无法在搜索框下方显示任何建议。我想知道是否有人可以帮助我解决这个问题?

顺便说一下,我希望建议限制是5.我怎么能这样做?

index.php的代码:

<html>
    <head>
        <title>
            Brandon's Search Engine
        </title>
        <style type="text/css">
            #suggestion {
                border: 1px solid black;
                visibility: hidden;
            }
            #suggestion a {
                font-size: 12pt;
                color: black;
                text-decoration: none;
                display: block;
                width: 450px;
                height: auto;
            }
            #suggestion a:hover {
                background-color: #dddddd;
            }
        </style>
    </head>
    <script type="text/javascript">
        function getSuggestion(q) {
            var ajax;
            if(window.XMLHttpRequest)//for ie7+, FF, Chrome
                ajax = new XMLHttpRequest();//ajax object
            else
                ajax = new ActiveXObject("Microsoft.XMLHTTP");//for ie6 and previous
            ajax.onreadystatechange = function {
                if(ajax.status == 200 && ajax.readyState == 4) {
                    document.getElementById("suggestion").innerHTML = ajax.responseText;
                }
            }
            ajax.open("GET", "suggestion.php?q=$query" + q, false);
            ajax.send();
        }
    </script>
    <body>
        <form method="GET" action="search.php">
            <input type="hidden" name="page" value="0" />
            <table align="center">
                <tr>
                    <td>
                        <h1><center>Brandon's Search Engine</center></h1>
                    </td>
                </tr>
                <tr>
                    <td align="center">
                        <input type="text" name="q" size="90"
                               onkeyup="getSuggestion(q)" autocomplete="off" />
                    </td>
                </tr>
                <tr>
                    <td align="center">
                        <input type="submit" value="Search" />
                        <input type="reset" value="Clear" />
                    </td>
                </tr>
            </table>
        </form>
        <div id="suggestion" size="90">
        </div>
    </body>
</html>

advicetion.php的代码:

<?php
include 'connect.php'; //connect with database
$query = $_GET["q"];
if($query != "")
{
$stmt = "SELECT * FROM searchengine WHERE title LIKE '%" . mysqli_real_escape_string($con,$query) . "%' OR link LIKE '%" . mysqli_real_escape_string($con,$query) . "%' LIMIT 0 , 10";
$result = mysqli_query($con,$stmt) or die(mysqli_error($con));
$number_of_result = mysqli_num_rows($result);
if ($number_of_result < 1) {
    echo "Your search did not match any documents. Please try different keywords.";
} else {
    //results found here and display them
    while ($row = mysqli_fetch_assoc($result))//show first 10 results
        $title = $row["title"];
        $link = $row["link"];
        echo "<div id='sugg-search-result'>";
        echo "<a href='$link' id='sugg-title'>" . $title . "</a>";
        echo "</div>";
    }
}
?>

提前致谢。

2 个答案:

答案 0 :(得分:0)

让我们从这开头:

// some common external JavaScript - learn now - common.js
//<![CDATA[
var doc = document, bod = doc.body;
var IE = parseFloat(navigator.appVersion.split('MSIE')[1]);
bod.className = 'js';
function E(e){
  return doc.getElementById(e);
}
//]]>

// this page external JavaScript - thispage.js
//<![CDATA[
var q = E(q);
function getSuggestion(){
  var xhr = new XMLHttpRequest || new ActiveXObject('Microsoft.XMLHTTP');
  xhr.onreadystatechange = function(){
    if(xhr.readyState == 4 && xhr.status == 200){
      E('suggestion').innerHTML = xhr.responseText;
    }
  }
  xhr.open('GET', 'suggestion.php?q='+q.value, false);
  xhr.send();
}
q.onkeyup = getSuggestion;
//]]>

现在你的HTML:

<!DOCTYPE html>
<html xmlns='http://www.w3.org/1999/xhtml' xml:lang='en' lang='en'>
  <head>
    <meta http-equiv='content-type' content='text/html;charset=utf-8' />
    <title>
        Brandon&#039;s Search Engine
    </title>
    <style type='text/css'>
      @import 'external.css';
    </style>
  </head>
<body class='njs'>
  <form method='GET' action='search.php'>
    <input type='hidden' name='page' value='0' />
    <table align='center'>
      <tr>
        <td>
          <h1><center>Brandon&#039;s Search Engine</center></h1>
        </td>
      </tr>
      <tr>
        <td align="center">
          <input type='text' name='q' id='q' maxlength='90' autocomplete='off' />
        </td>
      </tr>
      <tr>
        <td align='center'>
          <input type='submit' value='Search' />
          <input type='reset' value='Clear' />
        </td>
      </tr>
    </table>
  </form>
  <div id='suggestion'></div>
  <script type='text/javascript' src='common.js'></script>
  <script type='text/javascript' src='thispage.js'></script>
</body>
</html>

答案 1 :(得分:-1)

你遗失的php分隔符就在这里。

改变这个:

ajax.open("GET", "suggestion.php?q=$query" + q, false);

要:

ajax.open("GET", "suggestion.php?q=<?php echo $query;?>"+q, false);

更新回答:

keyup函数中,传递的参数不正确。

<input type="text" name="q" size="90" onkeyup="getSuggestion(q)" autocomplete="off" />

而是传递已键入的值:

<input type="text" name="q" size="90" onkeyup="getSuggestion(this.value)" autocomplete="off" />

改变这个:

ajax.open("GET", "suggestion.php?q=$query" + q, false);

要:

ajax.open("GET", "suggestion.php?q="+q, false);

jQuery ajax:

function getSuggestion(q){
$.ajax({
  type: "GET",
  url: "suggestion.php",
  data: {item:q},
  success:function(data){
  alert(data);
  $("#suggestion").html(data);
  }
  });

}

suggestion.php:

$value = $_GET['item'];

// enter the query here and echo the results

注意:不要忘记包含jQuery库。

相关问题