關於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);
               })
            }
        },
複製代碼

最後再從數據庫取出數據

相關文章
相關標籤/搜索