2017-08-28 33 views
0

當我對以下ajax請求使用POST方法時,它會拋出「Method not allowed」錯誤。如果我使用表單POST而不使用ajax,它會轉到正確的方法。如何在laravel和ajax中使用POST方法

在Router.php:

$this->post('TestPost','[email protected]'); 

看來,Ajax請求是:

$.ajax(
{   
type: "POST", 
url: 'TestPost', 
data: "{}", 
contentType: "application/json; charset=utf-8", 
dataType: "json", 
cache: false, 
success: function (data) { 
alert('hid post');  

SetHotandWorstData(data,'hotquantity'); 

}, 

error: function (msg) { 
alert('error'); 
alert(msg.responseText); 
} 
}); 

在控制器:

function TestPostMethod(Request $request) 
{ 
    $hotworstsalesdata = DB::table('100_INVOICEDETAIL')    
    ->select('100_INVOICEDETAIL.ITEMCODE','100_INVOICEDETAIL.ITEMNAME', 
DB::raw('SUM("100_INVOICEDETAIL"."QTY") as 
salesqty'), DB::raw('SUM("100_INVOICEDETAIL"."AMT") as salesamt')) 
    ->groupBy('100_INVOICEDETAIL.ITEMCODE','100_INVOICEDETAIL.ITEMNAME') 
    ->orderBy('salesqty') 
    ->take(10) 
    ->get(); 
    return Datatables::of($hotworstsalesdata)->make(true); 
} 
+0

也許Laravel是困惑,爲什麼你要發送JSON,當你可以只通過不使用郵政普通帖子陣列的字符串引號和刪除JSON內容類型?我知道Laravel有很多魔力,這是你決定使用它時會得到的東西之一。試試我說的話,看看會發生什麼。 –

回答

4

你應該通過 「_token」 在POST數據。 Laravel使用令牌進行跨站請求僞造(CSRF)攻擊。使用下面的代碼在你的AJAX請求

data: { _token: "{{ csrf_token() }}" } 

更新的答案:我的系統上

我已經重新創建同樣的場景與laravel 5.4和它的工作對我來說。

我的路線(web.php)代碼:

Route::post('/test_post', '[email protected]'); 

JavaScript代碼:

<script type="text/javascript"> 
    $.ajax({ 
     type: "POST", 
     url: '{{ url('/') }}/test_post', 
     data: { _token: "{{ csrf_token() }}" }, 
     contentType: "application/json; charset=utf-8", 
     dataType: "json", 
     cache: false, 
     success: function (data) { 
      console.log(data); 
     }, 

     error: function (msg) { 

      console.log(msg.responseText); 
     } 
    }); 
    </script> 

DashboardController文件是:

public function getData(Request $request) { 
    print_r($request);  
} 
+0

我改變了這樣的=>數據:{「_token」:「{{csrf_token()}}」},但仍然拋出錯誤 –

+0

試試這個:data:{_token:「{{csrf_token()}}」}我知道如果不工作 – Rajinder

+0

我試過像這樣=>類型:「POST」, url:'TestPost', data:{_token:「{{csrf_token()}}」}, contentType:「application/json; charset = utf-8「, –

0

最近我遇到錯誤與DELETE方法!我通過在html標題中設置csrf token來修復並獲取ajax。希望這能解決你的問題..

<html> 
<header> 
<meta name="csrf-token" content="{{ csrf_token() }}" /> 

在阿賈克斯,

$.ajaxSetup({ 
    headers: { 
     'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') 
    } 
});