ajax/laravel 从数据库搜索而不刷新

ajax/laravel search from DB without refresh

我的控制器

public function autoComplete(Request $request) {
    $query = $request->get('term','');

    $products=User::where('fullname','LIKE','%'.$query.'%')->get();
    $data=array();
    foreach ($products as $product) {
            $data[]=array('value'=>$product->fullname,'id'=>$product->id);
    }
    if(count($data))
         // return $data;
        return response()->json($data);
    else
        return ['value'=>'No Result Found','id'=>''];
}

js代码

  <script>
  $(document).ready(function() {
src = "{{ url('/')}}/users/searchhistory";
 $("#search_text").autocomplete({
    source: function(request, response) {
        $.ajax({
            url: src,
            dataType: "json",
            data: {
                term : request.term
            },
            success: function(data) {
                // response(data); it shows all array index 
                // $('form').append('<h1>'+data+'</h1>'); it gives me (object Object ) for each record
                // $('form').append('<h1>'+data.id+'</h1>'); it gives me undefined
                // $('form').append('<h1>'+data['id']+'</h1>'); it gives me undefined
                console.log(data);

            }
        });
    },
    minLength: 1,
});

});

当我搜索时,我在控制台上得到这个数组

(6) [{…}, {…}, {…}, {…}, {…}, {…}]
0:
   id: 1
   value: "ali"
   __proto__: Object
1:
   {value: "hassan", id: 2}
2:
   {value: "alikarimi", id: 4}
3:
   {value: "karimi", id: 5}
4:
   {value: "qasem", id: 7}
5:
   {value: "tagi", id: 8}
length: 6
__proto__: Array(0)

我如何使用它们来显示 ID 或名称。 我尝试了 data.id 和数据 ['id'] 但这两个都给我未定义的输出。

它是一个数组,所以你应该这样做:

console.log(data[0].id)

或者更好,你可以做一个for循环。

for (var i = 0; i < data.length; i++)
{
    console.log(data[i].id);
}