如何解决ThinkPHP中无法获取POST数据的问题?
- 内容介绍
- 文章标签
- 相关推荐
本文共计407个文字,预计阅读时间需要2分钟。
一、问题现象:提交表单后,通过request-param()或$this->request-param()获取不到POST数据,得到的是空数组。
二、问题原因:表单中没有设置enctype属性。在表单提交时,如果没有设置enctype=multipart/form-data,那么表单中的文件和特殊字符数据将无法正确传输。
一、问题现象
提交表单后,通过 request->param() 或 $this->request->param() 获取不到 post 数据,得到的是空数组。
二、问题原因
表单中没有设置 enctype 属性
在表单提交时,如果 enctype 属性没有设置,那么默认的数据传输方式是 application/x-www-form-urlencoded。现在,数据将被放置在 HTTP 请求头部而非请求体中。所以,在获取 post 数据时,我们需要使用 $this->request->post() 或者 request()->post()。
接口调用时没有设置请求头
在接口调用时,我们需要设置相应的请求头,比如 Content-Type:application/json,否则服务器无法解析数据。如果没有设置 Content-Type,则服务器默认为 application/x-www-form-urlencoded,而此时 post 的数据会放在 www.example.com/login'; $ch = curl_init(); $header = array( 'Content-Type: application/json', 'Content-Length: '.strlen(json_encode($data)) ); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data)); curl_setopt($ch, CURLOPT_HTTPHEADER, $header); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); $res = curl_exec($ch); curl_close($ch);
本文共计407个文字,预计阅读时间需要2分钟。
一、问题现象:提交表单后,通过request-param()或$this->request-param()获取不到POST数据,得到的是空数组。
二、问题原因:表单中没有设置enctype属性。在表单提交时,如果没有设置enctype=multipart/form-data,那么表单中的文件和特殊字符数据将无法正确传输。
一、问题现象
提交表单后,通过 request->param() 或 $this->request->param() 获取不到 post 数据,得到的是空数组。
二、问题原因
表单中没有设置 enctype 属性
在表单提交时,如果 enctype 属性没有设置,那么默认的数据传输方式是 application/x-www-form-urlencoded。现在,数据将被放置在 HTTP 请求头部而非请求体中。所以,在获取 post 数据时,我们需要使用 $this->request->post() 或者 request()->post()。
接口调用时没有设置请求头
在接口调用时,我们需要设置相应的请求头,比如 Content-Type:application/json,否则服务器无法解析数据。如果没有设置 Content-Type,则服务器默认为 application/x-www-form-urlencoded,而此时 post 的数据会放在 www.example.com/login'; $ch = curl_init(); $header = array( 'Content-Type: application/json', 'Content-Length: '.strlen(json_encode($data)) ); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data)); curl_setopt($ch, CURLOPT_HTTPHEADER, $header); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); $res = curl_exec($ch); curl_close($ch);

