【问题标题】:ajax/laravel search from DB without refresh从数据库中搜索 ajax/laravel 而不刷新
【发布时间】:2018-07-06 09:36:42
【问题描述】:

我的控制器

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 和 data['id'] 但这两者都给了我未定义的输出。

【问题讨论】:

  • 需要将数据传递给response回调...查看文档和示例

标签: php jquery ajax laravel ajaxform


【解决方案1】:

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

console.log(data[0].id)

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

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

【讨论】:

    猜你喜欢
    • 2021-02-11
    • 1970-01-01
    • 2019-05-03
    • 2017-06-19
    • 2016-10-07
    • 2013-05-27
    • 2016-09-03
    • 2020-09-16
    • 1970-01-01
    相关资源
    最近更新 更多