我使用以下代码实现了Laravel 5.1自动完成功能:
<script type="text/javascript">
$(document).ready(function () {
$("#utente").autocomplete({
minLength:3,
autoFocus: true,
source: '{{URL('utente')}}',
select: function( event, ui ) {
window.location.href = ui.item.url;
},
});
});
</script>
这是我的路线:
Route::any('utente', function(){
$term = Input::get('utente');
// 4: check if any matches found in the database table
$data = DB::table("tb_users")->distinct()->where('last_name', 'LIKE', $term.'%')->groupBy('last_name')->get();
foreach ($data as $v) {
$nome = $v->last_name . ' ' . $v->first_name;
$url = "clienti?utente=$v->id";
$return_array[] = array('value' => $nome, 'label' => $nome, 'url' => $url); }
// if matches found it first create the array of the result and then convert it to json format so that
// it can be processed in the autocomplete script
return Response::json($return_array);
});
这是用于渲染自动完成的fiedl。
<input type="text" id="utente" name="utente" placeholder="Cognome e Nome" class="form-control-utente" ></input>
问题是,这会在DB中获取所有结果...而不是与查询匹配的结果