我在products.blade中的laravel项目中创建了一个搜索字段。我的ajax也在那个页面里面。然而它不起作用,自动完成没有响应,如果我按下搜索按钮它刷新页面并保持不变。
我的路线是:
Route::get('autocomplete',array('as'=>'autocomplete','uses'=>'AutoCompleteController@index'));
Route::get('searchajax',array('as'=>'searchajax','uses'=>'AutoCompleteController@autoComplete'));
我的AutoCompleteController是:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Product;
class AutoCompleteController extends MainController {
public function index(){
return view('content.products');
}
public function autoComplete(Request $request) {
$query = $request->get('term','');
$products=Product::where('title','LIKE','%'.$query.'%')->get();
$data=array();
foreach ($products as $product) {
$data[]=array('value'=>$product->title,'id'=>$product->id);
}
if(count($data))
return $data;
else
return ['value'=>'No Result Found','id'=>''];
}
}
我的products.blade视图:
@extends ('master')
@section('content')
<div class="row">
<form class="navbar-form text-center " form method="GET" action=" ">
<input id="search_text" placeholder=" Search products" name="search_text" type="text" value="" style="width: 400px; height: 35px; border-radius: 5px ; padding-left: 12px;"><br><br>
<input class="btn btn-default " type="submit" value=" Search" >
</form>
</div>
<script>
$(document).ready(function() {
$("#search_text").autocomplete({
source: function(request, response) {
$.ajax({
url: "{{ route('searchajax') }}",
dataType: "json",
data: {
term : request.term
},
success: function(data) {
response(data);
}
});
},
minLength: 3,
});
});
</script>