jQuery UI自动完成显示"没有搜索结果"

时间:2015-07-19 00:55:27

标签: php mysql jquery-ui

我想使用jQuery UI Autocomplete显示来自mysql数据库的建议

我有以下表格

 <form action="search.php" method="POST">
        <input type="text" name="search" id="search-input">
        <input type="submit" value="Submit" id="submit">
 </form>

的search.php

    <?php 
require_once 'db.php';

$a = array();

    if (isset($_POST['search']) && !empty($_POST['search'])) {
        $search_param = trim($_POST['search']);

        $slct_search = $db->prepare("SELECT student_name FROM student_details WHERE student_name LIKE ?") or die($db->error);
        $slct_search->bind_param('s', $search_param);
        $slct_search->execute();        
        $res = $slct_search->get_result();  
        if($res->num_rows) {            
            while ($result = $res->fetch_object()) {
                $a[] = $result->student_name;
            }
            echo json_encode($a);
        } else {
            echo 'OOPS we had a problem';
        }   
    }
?>

search.php工作正常。它返回

  

[&#34;拉维&#34;&#34;拉维&#34;]

JS代码

    $(function() {
      $("#search-input").autocomplete({
        source: "search.php",
        minLength: 2
      }); 
    });

问题是当我开始输入立即显示的文本框时

  

没有搜索结果。

我也试过JQuery UI Autocomplete Search Results do not display

1 个答案:

答案 0 :(得分:0)

HTML

  <form action="" method="">
        <input type="text" name="search" id="search-input" autocomplete="off">
        <input type="submit" value="Submit" id="submit">
        <div id="empty-message"></div>
  </form>

现在 search.php

    $searchTerm = trim($_GET['term']);

    $query = $db->query("SELECT student_name FROM student_details WHERE student_name LIKE '%".$searchTerm."%' ORDER BY student_name ASC");


    while ($row = $query->fetch_object()) {
        $data[] = $row->student_name;
    }

    echo json_encode($data);

jquery ui自动完成仅使用$ _GET

所以我使用$ _GET ['term'],见下图

enter image description here

JS代码

$('#search-input').autocomplete({
    source: 'search.php',
    minLength: 2,
    response: function(event, ui) {
        // ui.content is the array that's about to be sent to the response callback.
        if (ui.content.length === 0) {
            $("#empty-message").text("No results found");
        } else {
            $("#empty-message").empty();
        }
    }
});