我想使用AJAX

时间:2019-01-22 12:05:20

标签: php ajax

我有一个使用AJAX和PHP的搜索框,它可以正常工作,但我想做的不仅仅是一次搜索,因此当我再次搜索时,它将把结果添加到表的上一个搜索中,而不是替换上一次搜索的结果。

在下面的代码中,当我运行它时,它将搜索数据库并在index.php页面上的表中返回结果,但是当我使用另一个条形码进行搜索时,它将带来结果,但会替换先前的结果,我想将新结果添加到之前带来的结果中。

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">

<html lang="pt" dir="ltr">

<head>

  <title>Search And Show Without Refresh</title>

  <meta HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=ISO-8859-1">
  <meta http-equiv="Content-Style-Type" content="text/css">

  <!-- JQUERY FROM GOOGLE API -->
  <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>

  <script type="text/javascript">
    $(function() {
      $("#lets_search").bind('submit', function() {
        var value = $('#str').val();
        $.post('process.php', {
          value: value
        }, function(data) {
          $("#search_results").html(data);
        });
        return false;
      });
    });
  </script>

</head>

<body>

  <div>
    HEADER
  </div>
  <div>
    <form id="lets_search" action="">
      Search:<input type="text" name="str" id="str">
      <input type="submit" value="send" name="send" id="send">
    </form>
    <div id="search_results"></div>
  </div>
  <div>
    FOOTER
  </div>

</body>

</html>

这是process.php代码this is the result am getting 此php代码照常只返回一个结果,并替换了已生成的结果

<?php

    $servername = "localhost";
    $username = "root";
    $password = "password";
    $dbname = "dbname";

    ############## Make the mysql connection ###########

    $conn = new mysqli($servername, $username, $password, $dbname);
    // Check connection

    #$db = mysql_select_db(DB) or die(DB_MSG_ERROR);

    $sel = ("
      SELECT *
      FROM total_items
      WHERE bar_code='" . $_POST['value'] . "'
    ");

    $res = $conn->query($sel);

    echo '<table>';

    while ($data = $res->fetch_array()) {

        echo '
      <tr style="background-color:pink;">
        <td style="font-size:18px;">' . $data[1] . '</td>
        <td style="font-size:18px;">' . $data[2] . '</td>
      </tr>';

    }

    echo '</table>';

?>

it is bringing only a single result and when I search again, it will replace the result generated before. I want it to add the new result to the previous result instead of replacing

1 个答案:

答案 0 :(得分:2)

代替

$("#search_results").html(data); // it replaces the data

$("#search_results").append(data); // it appends the data with previous data there
相关问题