搜索框与自动完成jQuery - 更新

时间:2017-10-05 09:47:30

标签: jquery jquery-ui-autocomplete

我正在尝试使用自动完成功能(jQuery)实现即时搜索框。正在从数据库中提取数据。我可以看到它正在通过,但由于某种原因自动完成功能无法正常工作。

HTML

<div class="ui-widget">
  <label style="color: white" for="searchBar">Skills: </label>
  <input id="searchBar">
</div>

PHP - Slim框架

$app->get('/ajaxsearchbox', function() {

    //$query = $_REQUEST['query'];
    $query = $_GET['query'];

    if (isset($query)) {

        $sql = DB::query("SELECT * FROM players WHERE playerName LIKE '%$query%'");

        foreach ($sql as $result[]) ;
    };
    echo json_encode(array("result" => $result));
});

的jQuery

$(document).ready(function() {
  $( "#searchBar" ).autocomplete({
    source: function(request, response) {
      $.getJSON("/ajaxsearchbox",{ query:request.term},response);
    },
    minLength: 0   
  });   
})

1 个答案:

答案 0 :(得分:0)

让您的Get请求返回更简单的数据

$app->get('/ajaxsearchbox', function() {

    //$query = $_REQUEST['query'];
    $query = $_GET['query'];

    if (isset($query)) {

        $sql = DB::query("SELECT * FROM players WHERE playerName LIKE '%$query%'");

        foreach ($sql as $result[]) ;
    };
    echo json_encode($result);
});

之后在Jquery自动完成中添加自定义渲染,如:

$(document).ready(function() {
    $( "#searchBar" ).autocomplete({
        source: function(request, response) {
            $.getJSON("/ajaxsearchbox",{ query:request.term},response);
        },
        minLength: 0,
        select: function( event, ui ) {
            $( "#searchBar" ).val( ui.item.playerName );
        },
    }).autocomplete( "instance" )._renderItem = function( ul, item ) {
       return $( "<li>" )
       .append( "<div>PlayerName : " + item.playerName + "</div>" )
       .appendTo( ul );
     };
   } );

}

点击此链接,了解有关处理自定义数据http://jqueryui.com/autocomplete/#custom-data

的详情