如何检索axios post请求发送的php中的变量 [英] How to retrieve variables in php sent by axios post request

查看:56
本文介绍了如何检索axios post请求发送的php中的变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要向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'];

这篇关于如何检索axios post请求发送的php中的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆