[英]Laravel Ajax Call through entire page
我正在尝试通过我的整个应用程序运行 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' => '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);
}
});
Url http://localhost/myApp/public/notification/all返回成功消息。
但是像这样的网址 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']);
});
});
您必须为每个 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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.