我是通过从数据库中选择数据并以json的形式获取响应来尝试自动完成,但我得到的只是内部服务器错误,这可能是csrf令牌的问题吗?
这是脚本
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script src="http://code.jquery.com/ui/1.11.4/jquery-ui.js" ></script>
<script type="text/javascript">
$(document).ready(function () {
$('input:text').bind({
});
$("#auto").autocomplete({
minLength:2,
source: '{{ URL('getdata') }}'
});
});
</script>
这在控制器中:
public function getData(){
$term = Input::get('term');
$data = DB::table('items')->distinct()->select('item_name')->where('word', 'LIKE', $term.'%')->groupBy('word')->take(10)->get();
foreach ($data as $v) {
$return_array[] = array('value' => $v->word);
}
return Response::json($return_array);
}
答案 0 :(得分:0)
getData函数存在问题,这个问题有效。
public function getData(){
$term = Input::get('term');
$data = DB::table('items')->distinct()->select('item_name')->where('item_name', 'LIKE', $term.'%')->groupBy('item_name')->take(10)->get();
foreach ($data as $v) {
$return_array[] = array('value' => $v->item_name);
}
return Response::json($return_array);
}
答案 1 :(得分:0)
inspector.js:44 GET http://127.0.0.1:8000/product/autocomplete?terms=d 500(内部服务器错误)# *这是我的控制器,
public function autosearch(Request $request){
// dd($request->all());
$query = $request->get('term','');
$allproducts = Product::where('product_title','LIKE','%'.$query.'%')->get();
$data = array();
foreach($allproducts as $product)
{
$data[] = array('value'=>$product->product_title,'id'=>$product->id);
}
if(count($data))
{
return $data;
}
else{
return ['value'=>"No Result Found",'id'=>''];
}
}
这是我的脚本标签:
<script>
$(document).ready(function(){
var path = "{{route('autosearch')}}"
$('#search_text').autocomplete({
source:function(request,response)
{
$.ajax({
url:path,
dataType:"JSON",
data:{
term:request.term
},
success:function(data)
{
response(data);
}
});
},
minLength:1,
});
});
</script>
这是我的 HTML 表单:
<div class="col d-none d-xl-block">
<label class="sr-only" for="searchproduct">Search</label>
<div class="input-group">
<input id="search_text" type="search" name="search" class="form-control py-2 pl-5 font-size-15 border-right-0 height-40 border-width-2 rounded-left-pill border-primary typeahead" placeholder="Search for Products" aria-label="Search for Products" aria-describedby="searchProduct1" autocomplete="off" required>
<div class="input-group-append">
<button class="btn btn-primary height-40 py-2 px-3 rounded-right-pill" type="submit" id="searchProduct1">
<span class="ec ec-search font-size-24"></span>
</button>
</div>
</div>
</div>