ThinkPHP6表单上传的数据获取 首先一个fORM表单中的Input控件需要存在对应的name值,然后method为post|get,action为要提交到的控制器的哪个方法 例如(本文的前端视图
首先一个fORM表单中的Input控件需要存在对应的name值,然后method为post|get,action为要提交到的控制器的哪个方法
<form method="post" action="/index.php/login/login" > <input type="text" name="username"><br> <input type="text" name="passWord"><br> <input type="submit" value="提交">form>
这个表单意为,要提交数据到login.php控制器下的login方法
表单中的请求参数通过Request
来获取,也可以使用原生的$_GET
或者 $_POST
来获取,然后大致分为请求对象调用,Facade调用,助手函数调用。
那么我们接下来对这三种方式都通过个小例子来验证:
请求对象调用分为两种,构造方法注入(即提供一个构造器和一个Request实例)和操作方法注入(通过函数参数注入)。
namespace app\controller;use app\BaseController;use think\Request; // 系统的think\Request对象class Login extends BaseController{ // request 实例 protected $request; // request 构造器注入方式 public function __construct(Request $request) { $this->request = $request; } public function login(){ return $this->request->param('username'); }}
这里注意别引入错了Request,构造方法注入的Request需要是think\Request
。
测试一下,ok,正确获取。
namespace app\controller;use app\BaseController;use think\Request; // 系统的think\Request对象class Login extends BaseController{ // 在方法参数上,将Request注入 public function login(Request $request){ return $request->param('username'); }}
、
在没有使用依赖注入的场合,可以通过Facade
机制来静态调用请求对象的方法(注意use
引入的类库区别)。
请求对象调用使用的是use think\Request;
,而静态调用使用的是use think\facade\Request;
。
namespace app\controller;use app\BaseController;use think\facade\Request; class Login extends BaseController{ public function login(){ // 静态调用 return Request::param('username'); }}
为了简化调用,系统还提供了request
助手函数,可以在任何需要的时候直接调用当前请求对象。
namespace app\controller;use app\BaseController;class Login extends BaseController{ public function login(){ // 助手函数调用 return request()->param('username'); }}
助手函数调用不需要引入使用其他的库。
通过原生的$_GET
和$_POST
来获取请求表单的参数。
namespace app\controller;use app\BaseController;class Login extends BaseController{ public function login(){ return $_POST['username']; }}
或者
namespace app\controller;use app\BaseController;class Login extends BaseController{ public function login(){ return $_GET['username']; }}
在tp6中,获取上传的表单参数有多种方式,请求对象调用,静态调用,助手函数调用以及使用原生的$_GET
和$_POST
均可。
但是需要注意的是,在使用请求对象调用是,引入的Request
应为think\Request
。静态调用时需要引入的Request
应为think\facade\Request
。助手函数调用和原生的$_GET
和$_POST
不需要引入Request
。
最后就是表单请求的action域,需要写为/入口文件/控制器名/方法(/index.php/login/login)
来源地址:https://blog.csdn.net/m0_63622279/article/details/130714826
--结束END--
本文标题: ThinkPHP6表单上传的数据获取的四种方式【请求对象调用,静态调用,助手函数调用,原生的get|post】
本文链接: https://www.lsjlt.com/news/392139.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
下载Word文档到电脑,方便收藏和打印~
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0