Javascript 整个页面的Laravel Ajax调用
我试图在整个应用程序中运行一个Ajax post调用,它将更新导航。在某些页面上它是有效的,但在另一些页面上它是无效的,可以这么说,我如何解决这个问题并使其全球化 我使用Laravel作为php框架Javascript 整个页面的Laravel Ajax调用,javascript,php,jquery,ajax,laravel,Javascript,Php,Jquery,Ajax,Laravel,我试图在整个应用程序中运行一个Ajax post调用,它将更新导航。在某些页面上它是有效的,但在另一些页面上它是无效的,可以这么说,我如何解决这个问题并使其全球化 我使用Laravel作为php框架 # Middleware group if user is logged in Route::group(['middleware' => 'auth'], function () { # Notifications Route::group(['prefix' =>
# Middleware group if user is logged in
Route::group(['middleware' => 'auth'], function () {
# Notifications
Route::group(['prefix' => 'notification', 'as' => 'notification.'], function () {
Route::post('number', ['as' => 'number', 'uses' => 'NotificationController@number']);
});
Route::group(['prefix' => 'relation', 'as' => 'relation.'], function () {
Route::get('show/{id}', ['as' => 'show', 'uses' => 'RelationController@show']);
});
});
在我的layouts/app.blade.php中,我包含了如下的js文件
<script src="{{ asset('js/liveUpdater.js') }}"></script>
@yield('javascript')
Url返回一条成功消息
但类似这样的url会返回错误消息:
您在路由前面加了
通知
,因此您的ajax请求应该指向通知/编号
:
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content'),
}
});
$.ajax({
url: 'notification/number',
type: 'post',
success: function(data) {
$('#number-of-notifications').text(data.unread);
},
error: function(data) {
console.log('error number ' + data.data);
}
});
此外,我认为(在组中)使用别名也没有什么帮助,因此我认为(为了简单起见)您可以:
Route::group(['middleware' => 'auth'], function () {
# Notifications
Route::group(['prefix' => 'notification'], function () {
Route::post('number', 'NotificationController@number']);
});
});
您必须为每个url路径定义路由路径和相应的控制器方法,如关系/显示和通知/全部:
Route::group(['middleware' => 'auth'], function () {
# Notifications
Route::group(['prefix' => 'notification'], function () {
Route::post('show/{show}', 'NotificationController@show']);
Route::post('number', 'NotificationController@number']);
Route::post('all ', 'NotificationController@all']);
});
});
ajax中的请求方法中存在错误。它应该是“GET”类型,或者在web.php中类似于Route::post('show/{id}'而不是Route::GET('show/{id}'
您的请求方法不匹配,这就是为什么其抛出405您在向定义为接受get请求的路由发出POST请求或向定义为接受POST的路由发出get请求时,会出现此错误。在这样的uri中,此错误不起作用:
http://localhost/app/public/relation/show/1
或此http://localhost/app/public/notification/all
如果我打开http://localhost/app/public/notification/all
它指向/app/public/notification/notification/number
例如,AHH…它们的定义与我在您提供的路由中可以清楚地看到的不同…它们只是Ajax URL将主题发布到错误的方向,我添加了以上述问题中的关系/显示路线为例
Route::group(['middleware' => 'auth'], function () {
# Notifications
Route::group(['prefix' => 'notification'], function () {
Route::post('number', 'NotificationController@number']);
});
});
Route::group(['middleware' => 'auth'], function () {
# Notifications
Route::group(['prefix' => 'notification'], function () {
Route::post('show/{show}', 'NotificationController@show']);
Route::post('number', 'NotificationController@number']);
Route::post('all ', 'NotificationController@all']);
});
});