我正在尝试通过我的整个应用程序运行 Ajax post 调用,它将更新导航。在某些页面上它可以工作,但在其他页面上却不能,我该如何解决这个问题并使其成为全局性的。
我正在使用 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' => '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')
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返回一条成功消息。
但是像这样的 url http://localhost/myApp/public/relation/show/1返回错误信息:
number /myApp/public/relation/show 405 Method Not Allowed
最佳答案
您在路由前添加了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', 'NotificationController@number']);
});
});
关于javascript - Laravel Ajax 调用整个页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46601613/