ajax文本框值无响应自动建议

时间:2017-12-07 09:12:35

标签: php jquery ajax

我试图创建一个自动建议AJAX框,但服务器没有响应。

<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<head>
<title></title>

    <?php
        include 'search.php';
    ?>

    <script>
    $(document).ready(function() {
      $("#textbox1").keyup(function() {
        $.ajax({
            type: "GET",
            url: "search.php",
            data: {textbox1: $(this).val()},
            success: function (data) {
                  $("#main").html(data);
            }
        });
      });
    });
    </script>

    <form method="POST">
              enter keyword to search<br>
              <input type="text" name="textbox1" id="textbox1">
              <br><br>
              <div id="main"></div>
    </form>

</head>
<body>

这是 search.php

<?php

    include 'connection.php';

    if ($_SERVER["REQUEST_METHOD"] == "POST")
    {
        $search_value = $_POST['textbox1'];
        $query = "SELECT username FROM users WHERE username LIKE '" . $search_value . "%'";
        $conn_status = mysqli_query($conn, $query);

        while($row = $conn_status->fetch_assoc())
        {
            echo $row['username'] . '<br>';
        }
    }

?>

1 个答案:

答案 0 :(得分:0)

你错过了

  1. 获取Ajax请求并在PHP中使用POST请求
  2. 第二个并不重要,但如果你在
  3. 中定义行动,这是一个好习惯

    更改代码如下

    <!DOCTYPE html>
    <html>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <head>
    <title></title>
    
        <?php
            include 'search.php';
        ?>
    
        <script>
        $(document).ready(function() {
          $("#textbox1").keyup(function() {
            $.ajax({
                type: "POST",
                url: "search.php",
                data: {textbox1: $(this).val()},
                success: function (data) {
                      $("#main").html(data);
                }
            });
          });
        });
        </script>
    
        <form method="POST" action="">
                  enter keyword to search<br>
                  <input type="text" name="textbox1" id="textbox1">
                  <br><br>
                  <div id="main"></div>
        </form>
    
    </head>
    <body>