2017-10-06 85 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