Ajax精炼搜索

时间:2016-12-21 11:56:59

标签: php ajax sorting search

我有一个运动日的表,其中有4列名称,房子,事件,结果。我没有创建和显示数据库的问题,但我希望能够在一个栏中搜索并使用AJAX自动搜索所有4列以查找搜索栏中的内容。我使用PHPmyadmin与mySQLI存储数据库。我能够在我想要的页面上显示数据库。我也希望当页面开始显示整个表格时,然后当你开始输入它时,只删除任何与搜索不匹配的项目。我之前从未使用过Ajax,因为它来自w3schools网站,所以很遗憾。 DB称为sports_day,该表称为full_results。这是我目前的代码。

    <script>
function showUser(str) {
    if (str == "") {
        document.getElementById("txtHint").innerHTML = "";
        return;
    } else {
        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 (this.readyState == 4 && this.status == 200) {
                document.getElementById("txtHint").innerHTML = this.responseText;
            }
        };
        xmlhttp.open("GET","results_query.php?q="+str,true);
        xmlhttp.send();
    }
}
</script>

<form>
search for pupil
<input type="text" size="30" name="user" onkeyup="showUser(this.value)">
<div id="livesearch"></div>
<br>
</form>

<div class="col-sm-12">

<div id="txtHint"><b> pupil's info will be listed here</b></div>

</div>

并在名为results_query.php的页面上显示此代码

<body>

<?php
$q = intval($_GET['q']);

$con = mysqli_connect("localhost","root","","sports_day");
if (!$con) {
    die('Could not connect: ' . mysqli_error($con));
}

mysqli_select_db($con,"sports_day");
$sql="SELECT * FROM full_results WHERE id = '".$q."'";
$result = mysqli_query($con,$sql);

echo '<tr>';
    echo '<th>NAME</th>';
    echo '<th>HOUSE</th>';
    echo '<th>EVENT</th>';
    echo '<th>RESULT</th>';
echo ' </tr>';
while($row = mysqli_fetch_array($result)) {
  echo "<tr>";
  echo "<td>" . $row['NAME'] . "</td>";
  echo "<td>" . $row['HOUSE'] . "</td>";
  echo "<td>" . $row['EVENT'] . "</td>";
  echo "<td>" . $row['RESULT'] . "</td>";
  echo "</tr>";
}
echo "</table>";
mysqli_close($con);
?>
</body>

目前发生的事情是没有显示任何表格,当我在搜索框中输入任何内容时,整个表格以及标题底部的纯文本以及表格的所有内容在一条长行中出现。

任何建议让我的代码工作将不胜感激!

谢谢!

2 个答案:

答案 0 :(得分:0)

如果您使用&#39; results_query.php &#39;文件仅用于从数据库获取数据,因此您不需要创建<body>标记。如果您只使用PHP,那么您可以轻松跳过任何平面HTML。这只是一个题外话:)

但是到了这一点。 您可以更改从数据库返回数据的方式。我认为,不是做很多echo,而是最好将结果添加到变量并在结尾回显变量。

    $data = '<tr>' . '<th>NAME</th>' . '<th>HOUSE</th>' . '<th>EVENT</th>' . '<th>RESULT</th>' . '</tr>';

    while($row = mysqli_fetch_array($result)) {
      $data .= '<tr>';
      $data .= '<td>' . $row['NAME'] . '</td>';
      $data .= '<td>' . $row['HOUSE'] . '</td>';
      $data .= '<td>' . $row['EVENT'] . '</td>';
      $data .= '<td>' . $row['RESULT'] . '</td>';
      $data .= '</tr>';
    }

    $data .= '</table>';
    mysqli_close($con);

    echo $data;

看看这是否有所改变。

如果在页面加载后显示整个表格,您将不得不稍微更改PHP和JavaScript代码。

您可以更改您的JS,以便在加载页面后从full_results表中获取所有内容。 有几种方法可以做到这一点,你可以在这里阅读它们:

pure JavaScript equivalent to jQuery's $.ready() how to call a function when the page/dom is ready for it

最简单的方法是这样做:

    <script>
        function showUser(str) {
            var url;
            var xmlhttp;

            if (str == "") { //if empty string - get all data
              url = "results_query.php";
            } else { //get particular data otherwise
              url = "results_query.php?q="+str;
            }

            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 (this.readyState == 4 && this.status == 200) {
                document.getElementById("txtHint").innerHTML = this.responseText;
              }
            }

            xmlhttp.open("GET", url, true);
            xmlhttp.send();
        }
    </script>

        <form>
        search for pupil
        <input type="text" size="30" name="user" onkeyup="showUser(this.value)">
        <div id="livesearch"></div>
        <br>
        </form>

        <div class="col-sm-12">

        <div id="txtHint"><b> pupil's info will be listed here</b></div>

        </div>

        <script>
           //calling your function with empty string because we want to get all data
           showUser("");
        </script>

在PHP文件中你可以这样做:

<?php
$q = 0;
//check if 'q' parameter was passed
if(isset($_GET['q'])) {
  $q = intval($_GET['q']);
}

$con = mysqli_connect("localhost","root","","sports_day");
if (!$con) {
    die('Could not connect: ' . mysqli_error($con));
}

mysqli_select_db($con,"sports_day");
$sql = ($q) ? "SELECT * FROM full_results WHERE id = '".$q."'" : "SELECT * FROM full_results";

现在,您的JavaScript函数将在加载页面后调用。 它将使用AJAX调用您的PHP脚本,此脚本应返回表中的所有数据。

($q) ? "SELECT * FROM full_results WHERE id = '".$q."'" : "SELECT * FROM full_results";行中,只需检查$q是否与0不同。如果没有传递参数,我们的变量将设置为0,因此每当$ q等于&#39; 0&#39;时,我们只想获取full_results的所有数据和特定数据否则。

我还添加了var xmlhttp因为它只是局部变量。 你可以在这里阅读更多相关内容:

https://stackoverflow.com/a/1471738/7301294

我希望它会对你有所帮助。 如果您有任何其他问题,请告诉我,不要害怕问。 祝你好运!

答案 1 :(得分:0)

解决方案会是这样的:

  • 保持HTML搜索表格不变。

    <form>
        search for pupil
        <input type="text" size="30" name="user" onkeyup="showUser(this.value)">
        <div id="livesearch"></div>
        <br>
    </form>
    
  •   

    ...我也想在页面启动时显示整个表格,然后当你开始输入时,只删除任何与搜索不匹配的项目。

    请在此处查看此<div>部分,

    <div class="col-sm-12">
        ...
    </div>
    

    您没有在此<div>部分中添加任何内容。首先,您必须在此部分中显示整个表,稍后您可以使用AJAX请求过滤掉该表。另外,为此<div>部分指定 id ,以便您可以更轻松地将AJAX响应放入此<div>部分。因此,此<div>部分的代码将如下所示:

    <div class="col-sm-12" id="pupil-info">
    <?php
        $con = mysqli_connect("localhost","root","","sports_day");
        if (!$con) {
            die('Could not connect: ' . mysqli_error($con));
        }
    
        mysqli_select_db($con,"sports_day");
        $sql = "SELECT * FROM full_results";
        $result = mysqli_query($con,$sql);
    
        echo '<table>';
        echo '<tr>';
            echo '<th>NAME</th>';
            echo '<th>HOUSE</th>';
            echo '<th>EVENT</th>';
            echo '<th>RESULT</th>';
        echo ' </tr>';
        while($row = mysqli_fetch_array($result)) {
          echo "<tr>";
          echo "<td>" . $row['NAME'] . "</td>";
          echo "<td>" . $row['HOUSE'] . "</td>";
          echo "<td>" . $row['EVENT'] . "</td>";
          echo "<td>" . $row['RESULT'] . "</td>";
          echo "</tr>";
        }
        echo "</table>";
        mysqli_close($con);
    ?>
    </div>
    
  • 以下列方式更改您的Javascript / AJAX代码,

    <script>
        function showUser(str){
            var str = str.trim();
            var xmlhttp;
            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 (this.readyState == 4 && this.status == 200) {
                    document.getElementById("pupil-info").innerHTML = this.responseText;
                }
            };
            xmlhttp.open("GET","results_query.php?q="+encodeURIComponent(str),true);
            xmlhttp.send();
        }
    </script>
    

    请注意您应该使用encodeURIComponent()函数对用户输入的str值进行编码,然后再将其传递到 results_query.php 页面。< / p>

  • 最后,在 results_query.php 页面处理您的AJAX请求,如下所示:

    <?php
    
        $con = mysqli_connect("localhost","root","","sports_day");
        if (!$con) {
            die('Could not connect: ' . mysqli_error($con));
        }
    
        mysqli_select_db($con,"sports_day");
        $sql = "SELECT * FROM full_results";
        if(isset($_GET['q']) && !empty($_GET['q'])){
            $sql .= "  WHERE CONCAT(id, NAME, HOUSE, EVENT, RESULT) LIKE '%".$_GET['q']."%'";
        }
        $result = mysqli_query($con,$sql);
    
        echo '<table>';
        echo '<tr>';
            echo '<th>NAME</th>';
            echo '<th>HOUSE</th>';
            echo '<th>EVENT</th>';
            echo '<th>RESULT</th>';
        echo ' </tr>';
        if(mysqli_num_rows($result)){
            while($row = mysqli_fetch_array($result)) {
                echo "<tr>";
                    echo "<td>" . $row['NAME'] . "</td>";
                    echo "<td>" . $row['HOUSE'] . "</td>";
                    echo "<td>" . $row['EVENT'] . "</td>";
                    echo "<td>" . $row['RESULT'] . "</td>";
                echo "</tr>";
            }
        }else{
            echo "<tr>";
                echo "<td colspan='4' style='text-align:center;'>No records found</td>";
            echo "</tr>";
        }
        echo "</table>";
        mysqli_close($con);
    
    ?>
    

旁注:了解prepared statement因为您的查询现在容易受到SQL注入的影响。另请参阅how you can prevent SQL injection in PHP