【发布时间】: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