Last active
September 22, 2015 06:07
-
-
Save MicroHank/e79c2ee55185a1190c14 to your computer and use it in GitHub Desktop.
Laravel 實作路由 post 設定
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
剛開始接觸 Laravel,第一個卡關的地方是路由的 post 設定,仔細研究官網文件後,終於成功了。 | |
以下提供 form post 及 ajax post 範例: | |
路由設定 | |
Route::post('testpost/', 'UserController@testpost'); | |
(1) form 表單 post | |
送出一個名字欄位至 testpost/ 頁面,因為 Laravel 為了防止跨網站的 post 請求, | |
於是在中介層會檢查 CSRF token 是否符合,因此要在表單中增加一個 hidden 欄位,其值是 csrf_token()。 | |
<form action="/testpost" method="POST"> | |
<input type="text" name="name" value="我的名字" /> | |
<input type="submit" value="SEND" /> | |
<input type="hidden" name="_token" value="<?php echo csrf_token(); ?>" /> | |
</form> | |
利用 Request 物件去接變數 $request->input('name'),順利取得 post 變數。 | |
(2) ajax post | |
如果使用 ajax call 後端 API,官網提供一個方法,在使用到 ajax 的頁面,加入 meta tag,其 content 值為 csrf token。 | |
<head> | |
<meta name="csrf-token" content="<?php echo csrf_token(); ?>"> | |
</head> | |
使用 ajax 時,加入 headers,這個物件內要指定 X-CSRF-TOKEN 欄位,把 meta 內的值取出來。(其實我覺得也可放在 hidden input啦) | |
$.ajax({ | |
url: 'your api', | |
type: 'POST', | |
data: your data, | |
headers: { | |
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') | |
}, | |
success:function(data){...}, | |
error:function(jqXHR, textStatus, errorThrown){...}, | |
}) ; | |
以上,終於成功使用 post。 | |
參考官網:http://laravel.tw/docs/5.1/routing#csrf-x-xsrf-token |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment