如何检索由axios post请求发送的php中的变量

Rak*_*ali 7 javascript php ajax vue.js axios

我想向PHP脚本发送POST请求.我正在使用Axios:

axios.post('inc/vote.php', {
    id: this.selected,
}) .then(function (response) {
    console.log(response);
});
Run Code Online (Sandbox Code Playgroud)

在PHP文件中,我尝试这样的东西从axios中检索id变量:

$id = $_POST['id'];
Run Code Online (Sandbox Code Playgroud)

但似乎没有做任何事情.

从请求中检索变量的正确方法是什么?

小智 15

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);
  });
Run Code Online (Sandbox Code Playgroud)

后端解决方案 如果您有兴趣将请求体作为关联数组,您可以使用:

$data = json_decode(file_get_contents("php://input"), TRUE);
$id = $data['id'];
Run Code Online (Sandbox Code Playgroud)

  • 你救了我的工作,谢谢 (2认同)