我正在进行实时搜索,用户可以搜索商家。
这可以使用ajax并显示结果但是我得到一个错误,即存在TokenMismatchException。
这是我的代码:
的Ajax:
function search_data(search_value) {
$.ajax({
url: '/searching/' + search_value,
method: 'POST',
headers: {
'X-CSRFToken': $('meta[name="token"]').attr('content')
}
}).done(function(response){
$('#results').html(response); // put the returning html in the 'results' div
});
}
控制器:
public function search($search) {
$search_text = $search;
if ($search_text==NULL) {
$data= Business::all();
} else {
$data=Business::where('name','LIKE', '%'.$search_text.'%')->get();
}
return view('results')->with('results',$data);
}
}
路线::
Route::get('/', function () {
return view('auth/login');
});
Route::group(['middleware' => ['auth']], function () {
Route::get('tfgm', 'GuzzleController@tfgm')->name('tfgm');;
Route::get('odeon', 'GuzzleController@odeon')->name('odeon');;
Route::get('chronicle', 'GuzzleController@oldham_chronicle')->name('chronicle');;
Route::get('smokeyard', 'GuzzleController@smokeyard')->name('smokeyard');;
Route::get('profile/', 'ProfileController@checkid')->name('profile');;
Route::get('create/business', 'BusinessController@addBusiness')->name('createBusiness');
Route::get('business/list', 'BusinessController@viewBusiness')->name('viewBusiness');
Route::get('business/{id}', 'BusinessController@displayBusiness')->name('displayBusiness');
Route::post('/searching/{search}', 'SearchController@search');
Route::post('update', 'ProfileController@updateProfile');
Route::post('create', 'BusinessController@createBusiness');
Route::post('image', 'ImageController@image');
Route::post('test2', 'ImageController@gallery');
Route::post('markers', 'BusinessController@saveMarkers');
Route::post('reviews', 'BusinessController@saveReviews');
});
Auth::routes();
Route::get('/home', 'HomeController@index')->name('home');
Route::get('/redirect/{provider}', 'SocialAuthController@redirect');
Route::get('/callback/{provider}', 'SocialAuthController@callback');
master.blade.php
<head>
<meta name="csrf-token" content="{{ csrf_token() }}" />
</head>
<form action="/search" method="get" autocomplete="off" class="navbar-form navbar-left">
<div class="form-group">
<input type="text" class="form-control" id="search_text" onkeyup="search_data(this.value, 'result');" placeholder="Search">
</div>
<div id="result">
@include('results')
</div>
</div>
</form>
答案 0 :(得分:3)
你的行必须是
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
答案 1 :(得分:1)
在您的ajax代码中,您编写的X-CSRFToken
错误。正确是X-CSRF-TOKEN
始终在脚本文件中使用以下代码
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
答案 2 :(得分:0)
将X-CSRFToken更改为X-CSRF-TOKEN