donglu4633
2018-03-02 13:47
浏览 45

如何检索由axios发送请求发送的php中的变量[重复]

This question already has an answer here:

I want to send a POST request to a PHP script. I am using Axios:

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

In the PHP file I am trying something like this to retrieve that id variable from axios:

$id = $_POST['id'];

But seems it is not doing anything.

What is the correct way to retrieve variables from the request?

</div>

图片转代码服务由CSDN问答提供 功能建议

此问题已经存在 这里有一个答案:

  • Axios发布参数不能被$ _POST读取 3 answers

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

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

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

      $ id = $ _POST ['id']; 
       
     
     

    但似乎没有做任何事情 。

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

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • doufulian4076 2018-03-02 14:10
    已采纳

    Axios sends data as a JSON inside request body not as a Form Data. So you can't access the post data using $_POST['id'].

    Frontend Solution

    To be able to access data using $_POST['id'] you have to use FormData as the following:

    var form = new FormData();
    form.append('id', this.selected);
    axios.post('inc/vote.php', {
        form
      }) .then(function (response) {
        console.log(response);
      });
    

    Backend Solution if you are interested in getting the request body as associative array you can use:

    $data = json_decode(file_get_contents("php://input"), TRUE);
    $id = $data['id'];
    
    点赞 打赏 评论

相关推荐 更多相似问题