php jQuery autocomplete在laravel中运行不正常

时间:2016-06-19 12:35:08

标签: javascript php jquery laravel autocomplete

我一直在努力为自己的位置文字字段添加自动填充,问题是当我在其上键入任何字词时,它始终显示所有结果。

这是我的javascript:

<script type="text/javascript">
    $(function(){
        $("#Location").autocomplete({
            source: "{{ route('search.autocomplete') }}",
            minLength: 3,
            select: function(event, ui){
                $("#Location").val(ui.item.value);
             }
        });
    });
</script>

这是route.php

Route::get('search/autocomplete', ['uses' => 'SearchController@autocomplete', 'as' => 'search.autocomplete']);

这是searchController

public function autocomplete(Request $request){
        $term = $request->get('Location');

        $provinces = DB::table('provinces')->where('ProvinceName', 'LIKE', '%'. $term .'%')
        ->orderBy('ProvinceName', 'desc')
        ->get();

        $results = [];
        foreach ($provinces as $province) {
            $results[] = ['id' => $province->id, 'value' => $province->ProvinceName];
        }
        return response()->json($results);
}

这是search.blade.php

<div class="form-group col-md-4">
                Location: {!!Form::text('Location', Request::get('Location'), ['class' => 'form-control', 'placeholder' => 'What is your location?', 'id' => 'Location', 'style' => 'width: 250px;'])!!}
</div>

2 个答案:

答案 0 :(得分:1)

好的,我解决了我的问题,我改变了

route.php

Route::get('search/autocomplete', 'SearchController@autocomplete');

SearchController

if ($request->ajax()) {
        $term = Input::get('term');

        $results = array();  

        $queries = DB::table('provinces')
            ->where('ProvinceName', 'LIKE', '%'.$term.'%')
            ->take(5)->get();

        foreach ($queries as $query)
        {
            $results[] = [ 'id' => $query->id, 'value' => $query->ProvinceName ];
        }
        return Response::json($results);
}

和我的Javascript

<script type="text/javascript">
    $(function()
    {
         $( "#Location" ).autocomplete({
          source: "{{ url('search/autocomplete') }}",
          minLength: 3,
          select: function(event, ui) {
            $('#Location').val(ui.item.value);
          }
        });
    });
</script>

答案 1 :(得分:0)

  

具有标签和值属性的对象数组:[{label:“Choice1”,value:“value1”},...]

     

标签属性显示在建议菜单中。当用户选择项目时,该值将插入到input元素中。如果仅指定了一个属性,则它将用于两者,例如,如果仅提供值属性,则该值也将用作标签。

更改

$results[] = ['id' => $province->id, 'value' => $province->ProvinceName];

$results[] = ['value' => $province->id, 'label' => $province->ProvinceName];

$("#Location").val(ui.item.value);

$("#Location").val(ui.item.label);

在前端使用id

ui.item.value