Axios发送POST请求到PHP
1、请求
axios.post('/controller/login.php', {
username: this.form.username,
password: this.form.password
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
});
2、使用下边的方式接收参数,不生效,接收到的为空
<?php
public function process(): void
{
$username = $_POST['username']; // does not work
}
3、解决方法,使用php://input
public function process(): void
{
$request_body = file_get_contents('php://input');
$data = json_decode($request_body, true);
$username = $data['username']; // Works!
}
参考手册:https://zerowp.com/sending-axios-parameters-with-a-post-request-in-php/
或者采用URLSearchParams,如下:
const params = new URLSearchParams();
params.append('title', this.queryForm.title);
params.append('solution', this.queryForm.solution);
params.append('content', this.queryForm.content);
params.append('eventNo', this.queryForm.eventNo);
params.append('pageNo', pageNo);
params.append('selectProductIds', selectProductIds);
this.loadingList = true;
axios({
url: '/queryPage',
method: 'POST',
headers: {'Content-type': 'application/x-www-form-urlencoded'},
data: params
})
.then(function (response) {
if (response.data.code === 0) {
that.tableData = response.data.data.records;
that.total = response.data.data.total;
} else {
that.$message({type: 'error', message: response.data.msg});
that.tableData = [];
}
that.loadingList = false;
})
.catch(function (error) {
that.loadingList = false;
that.$message("获取数据失败" + error);
});