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

由于最近一直在学习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代码的状况下有什么解决办法呢?

一、经过实例化一个FormData把数据放入就能够了(推荐)javascript

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);
                    })
            }
        },
复制代码
  • 那么数据就能够成功传递过去,存进数据库了,使用起来方便简单。
    二、在项目中安装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);
               })
            }
        },
复制代码

最后再从数据库取出数据

相关文章
相关标签/搜索