参见英文答案 > Axios posting params not read by $_POST 3个
我想向PHP脚本发送POST请求.我正在使用Axios:
axios.post('inc/vote.php', {
id: this.selected,
}) .then(function (response) {
console.log(response);
});
在PHP文件中,我尝试这样的东西从axios中检索id变量:
$id = $_POST['id'];
但似乎没有做任何事情.
从请求中检索变量的正确方法是什么?
解决方法:
Axios在请求体内将数据作为JSON发送,而不是作为表单数据.因此,您无法使用$_POST [‘id’]访问帖子数据.
前端解决方案
为了能够使用$_POST [‘id’]访问数据,您必须使用FormData,如下所示:
var form = new FormData();
form.append('id', this.selected);
axios.post('inc/vote.php', {
form
}) .then(function (response) {
console.log(response);
});
后端解决方案
如果您有兴趣将请求体作为关联数组,您可以使用:
$data = json_decode(file_get_contents("php://input"), TRUE);
$id = $data['id'];
【说明】:本文章由站长整理发布,文章内容不代表本站观点,如文中有侵权行为,请与本站客服联系(QQ:254677821)!