2017-10-06 80 views
1

我想通过我的整个应用程序运行一个Ajax调用,它应该更新导航。在一些页面上它可以工作,但在另一些页面上它却没有,我该如何解决这个问题并使其成为全球性的。Laravel Ajax调用整个页面

我使用Laravel作为php框架。

# 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' => '[email protected]']); 
    }); 
    Route::group(['prefix' => 'relation', 'as' => 'relation.'], function() { 
     Route::get('show/{id}', ['as' => 'show', 'uses' => '[email protected]']); 
    }); 
}); 

在我的布局/ app.blade.php我包括JS文件这样

<script src="{{ asset('js/liveUpdater.js') }}"></script> 
@yield('javascript') 

的liveUpdater AJAX功能

$.ajaxSetup({ 
    headers: { 
     'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content'), 
    } 
}); 
$.ajax({ 
    url: 'number', 
    type: 'post', 
    success: function(data) { 
     $('#number-of-notifications').text(data.unread); 
    }, 
    error: function(data) { 
     console.log('error number ' + data.data); 
    } 
}); 

网址http://localhost/myApp/public/notification/all返回成功信息。

但是这样http://localhost/myApp/public/relation/show/1例如一个URL返回一个错误信息:

number 
/myApp/public/relation/show 
405 
Method Not Allowed 
+0

当您向定义为接受GET请求的路由发出POST请求或向定义为接受POST的GET请求发送POST请求时,您会收到此错误 –

回答

1

您前缀与notification路线让你的Ajax请求应指向notification/number

$.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', '[email protected]']); 
    }); 
}); 

Routing groups docs

+0

这不适用于这样的URI: 'http:// localhost/app/public/relation/show/1'或这个'http:// localhost/app/public/notification/all'它返回一个404,如果我打开'http:// localhost/app/public/notification/all'它指向'/ app/public/notification/notification/number'例如 – Jaan

+0

啊......它们没有被定义,因为我可以在你提供的路线中清楚地看到它们...... –

+0

它们是但是Ajax URL发布了错误的方向,我在上面的问题中添加了关系/ Show路由作为示例 – Jaan

0

您已经定义为关系/节目和通知/所有像每一个URL路径的路由路径和相应的控制方法:

Route::group(['middleware' => 'auth'], function() { 
    # Notifications 
    Route::group(['prefix' => 'notification'], function() { 
     Route::post('show/{show}', '[email protected]']); 
     Route::post('number', '[email protected]']); 
     Route::post('all ', '[email protected]']); 
    }); 
}); 
0

错误在您的请求方法阿贾克斯。它应该是类型:“GET”,或在您的web.php像路线:: post('显示/ {id}'而不是Route :: get('show/{id}'

您的请求方法是不匹配,为什么它抛出405