关于PHP无法获取axios中post提交的数据

1,131 阅读1分钟

因为最近一直在学习vue所以交互使用的是官方推荐的axios,在jquery中使用ajax时收发数据都没有问题,但是使用axiospost方法时发现一些问题,根据自己的理解记录一下。

  • 一开始先用固定数据做测试,在vue中我是这样写的
        methods:{
            axios_post:function(){
               axios
               .post('https://www.xxxxxx.cn/xx/xx.php',{
                   UserName:'xipengheng',
                   msg:'我是一头长颈鹿,我爱上树',
                   msgTime:'2019.10.23'
               })
               .then(res=>{
                   console.log(res);
               })
            }
        },
  • 发现PHP是获取不到值的。
  $UserName='"'.$_POST['UserName'].'"';
  $msg='"'.$_POST['msg'].'"';
  $msgTime='"'.$_POST['msgTime'].'"';
  • 那么自然而然,PHP中我的SQL语句是没有数据的,因此也没法往数据库中存储数据 测试结果

那么在不更改PHP代码的情况下有什么解决办法呢?

1、通过实例化一个FormData把数据放入就可以了(推荐)

        methods: {
            axios_post:()=> {
                var params = new FormData();
                params.append('UserName', 'xipengheng');
                params.append('msg', '我是一头长颈鹿,我爱上树');
                params.append('msgTime', '2009.09.09');
                axios
                    .post('https://www.xipengheng.cn/AAA/liuyan.php',params)
                    .then(res => {
                        console.log(res);
                    })
            }
        },
  • 那么数据就可以成功传递过去,存进数据库了,使用起来方便简单。 2、在项目中安装qs ,利用数据转化为qs.stringtry({}),也可以实现
        methods:{
            axios_post:()=>{
               axios
               .post('https://www.xipengheng.cn/AAA/liuyan.php',qs.stringify({
                   UserName:'xipengheng',
                   msg:'我是一头长颈鹿,我爱上树',
                   msgTime:'2009.99.09'
               }))
               .then(res=>{
                   console.log(res);
               })
            }
        },

最后再从数据库取出数据