我在当前项目中使用typeahead以及简单的查询搜索。简单的查询搜索工作得很好,但是,预先输入是部分工作,即SearchController @ autocomplete正在使用JSON进行响应,而在app.blade.php中,我有一个typeahead jquery脚本,脚本不会将json渲染/转换为HTML元素。
即使控制台也没有出错。我无法理解问题的幕后故事。我通过源代码提供所有内容。
app.blade.php
<script src="/js/jquery.min.js"></script>
<script src="/js/bootstrap.min.js"></script>
<script src="/js/typeahead.js"></script>
<script type="text/javascript">
var path = "{{ route('autocomplete') }}";
$('input.typeahead').typeahead({
source: function (query, process) {
return $.get(path, { query: query }, function (data) {
return process(data);
});
}
});
</script>
@yield('scripts')
</body>
</html>
navbar.blade.php
<form class="navbar-form navbar-left" role="search" action="/search" autocomplete="off">
<div class="form-group">
<input type="text" class="typeahead form-control" id="query" placeholder="Search Staff By Name, Designation, Department" name="query" value="{{Request::input('query')}}">
</div>
<button type="submit" class="btn btn-default">Submit</button>
</form>
路由/ web.php
/ ** *搜索控制器启动 * /
Route::get('/search', 'SearchController@getResults');
Route::get('/autocomplete',[
'uses'=>'SearchController@autocomplete',
'as'=>'autocomplete'
]);
/**
* Search Controller Ends
*/
SearchController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Auth;
use App\User;
use DB;
class SearchController extends Controller
{
public function getResults(Request $request)
{ $query = $request->input('query');
if(!$query){
return redirect('/home');
}
$users = User::where(DB::raw("CONCAT(first_name,'',last_name)"), '
LIKE', "%{$query}%")
->orwhere('name', 'LIKE', "%{$query}%")
->orwhere('department', 'LIKE', "%{$query}%")
->orwhere('designation', 'LIKE', "%{$query}%")
->orwhere('email', 'LIKE', "%{$query}%")
->orwhere('phone', 'LIKE', "%{$query}%")
->get();
return view('search')->with('users', $users);
}
public function autocomplete(Request $request){
$data = User::where("name","LIKE","%{$request->input('query')}%")->get();
return response()->json($data);
}
}
一些屏幕截图