- ThinkPHP實戰
- 夏磊
- 330字
- 2020-11-28 18:26:55
4.9 HTTP請求方法
很多情況下,需要判斷當前HTTP請求方法是否為GET、POST、PUT或DELETE,以此對同一個URL地址針對不同的請求方法來實現不同的響應。ThinkPHP內置了一些常量用來判斷請求方法,如表4-1所示。
表4-1

編輯Application/Home/Controller/IndexController.class.php方法,代碼如下:
<? php namespace Home\Controller; use Think\Controller; class IndexController extends Controller { public function index() { $this->redirect('login', 'role=admin', 3, ’請登錄’); } public function bind($id = 1) { echo U('Blog/view', array('id' => 1), 'shtml'); } public function login() { if (IS_POST) { echo ’當前為POST請求方法,需要處理登錄邏輯’; } else if (IS_GET) { echo ’當前為空GET請求方法,需要顯示登錄頁面’; } else { echo ’非法請求’; } } }
打開瀏覽器訪問http://localhost/chapter-4/Home/Index/login,輸出“當前為空GET請求方法,需要顯示登錄頁面”。
如何測試POST請求呢?這里使用表單來進行處理,在chapter-4的根目錄下新建post.html,代碼如下:
<! DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Post</title> </head> <body> <form action="http://localhost/thinkphp-inaction/chapter-4/Home/Index/login" method="post"> <button>提交</button> </form> </body> </html>
打開瀏覽器訪問http://localhost/chapter-4/post.html,點擊“提交”按鈕,輸出“當前為POST請求方法,需要處理登錄邏輯”,如此便實現了“相同URL根據不同請求方法實現不同響應”的功能。
推薦閱讀
- Boost程序庫完全開發指南:深入C++”準”標準庫(第5版)
- ReSharper Essentials
- vSphere High Performance Cookbook
- Mastering QGIS
- 羅克韋爾ControlLogix系統應用技術
- Visual Basic程序設計實驗指導(第4版)
- PHP+MySQL網站開發項目式教程
- Big Data Analytics
- Learn React with TypeScript 3
- D3.js 4.x Data Visualization(Third Edition)
- Learning PHP 7
- Python青少年趣味編程
- C語言程序設計
- OpenCV 3.0 Computer Vision with Java
- 超好玩的Scratch 3.5少兒編程