te')); return $arr; } /* 遍历用户所有主题 * @param $uid 用户ID * @param int $page 页数 * @param int $pagesize 每页记录条数 * @param bool $desc 排序方式 TRUE降序 FALSE升序 * @param string $key 返回的数组用那一列的值作为 key * @param array $col 查询哪些列 */ function thread_tid_find_by_uid($uid, $page = 1, $pagesize = 1000, $desc = TRUE, $key = 'tid', $col = array()) { if (empty($uid)) return array(); $orderby = TRUE == $desc ? -1 : 1; $arr = thread_tid__find($cond = array('uid' => $uid), array('tid' => $orderby), $page, $pagesize, $key, $col); return $arr; } // 遍历栏目下tid 支持数组 $fid = array(1,2,3) function thread_tid_find_by_fid($fid, $page = 1, $pagesize = 1000, $desc = TRUE) { if (empty($fid)) return array(); $orderby = TRUE == $desc ? -1 : 1; $arr = thread_tid__find($cond = array('fid' => $fid), array('tid' => $orderby), $page, $pagesize, 'tid', array('tid', 'verify_date')); return $arr; } function thread_tid_delete($tid) { if (empty($tid)) return FALSE; $r = thread_tid__delete(array('tid' => $tid)); return $r; } function thread_tid_count() { $n = thread_tid__count(); return $n; } // 统计用户主题数 大数量下严谨使用非主键统计 function thread_uid_count($uid) { $n = thread_tid__count(array('uid' => $uid)); return $n; } // 统计栏目主题数 大数量下严谨使用非主键统计 function thread_fid_count($fid) { $n = thread_tid__count(array('fid' => $fid)); return $n; } ?>javascript - Passing data from Vue.js to PHP using Axios - Stack Overflow
最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Passing data from Vue.js to PHP using Axios - Stack Overflow

programmeradmin1浏览0评论

I am trying to transmit some data from a GUI done in Vue.js to a PHP file using Axios. I tried both with GET and POST parameters but it does not work:

I type the data in this index.php form:

index.php:

<!DOCTYPE HTML>
<HTML>
<head>
    <script src=""></script>
    <script src=".18.0/axios.js"></script>
    <link rel="stylesheet" href=".0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
</head>
<BODY>
    <div id="container" class="container">
        <div>
            <label>First name:</label><br/>
            <input type="text" v-model='newPerson.firstName'>
        </div>
        <div>
            <label>Last name: </label><br/>
            <input type="text" v-model="newPerson.lastName">
        </div>
        <button v-on:click="sendIdentity()">Submit</button>       
    </div>    
    <script src="myjscode.js"></script>
</BODY>
</HTML>

myjscode.js:

When I press the button to submit the data, I see the right output in console.log(response.data):

let vm = new Vue({
    el: "#container",
    data: {
        newPerson: {
            firstName: '',
            lastName: ''
        }
    },
    methods: {
        sendIdentity: function() {
            let personForm = vm.toFormData(vm.newPerson);
            axios.post('phpfile.php', personForm)
                .then( function(response) {
                    console.log(response.data)
                });
        },
        toFormData: function(obj) {
            let formData = new FormData();
            for(let key in obj) {
                formData.append(key, obj[key]);
            }
            return formData;
        }
    }
});

phpfile.php:

On this file, I am rather performing an insertion into a MySQL table, however it never takes effect. I removed the MySQL code and let only what follows, where I notice I always get the message Data not received when I run this file:

<?php
if( isset($_POST['firstName']) && isset($_POST['lastName'])){
   echo $_POST['firstName'];
   echo $_POST['lastName'];      
} else {  
   echo 'Data not received';
}
?>

What am I missing?

Update:

I noticed when I changed the myjscode.js above like ths:

axios.post('phpfile.php?todo=something', ...)

And then I change phpfile.php to

<?php

if( isset($_GET['todo']) ){
   echo $_GET['todo'];
} else {
   echo 'No todo';
}
?>

I am getting No todo always displayed on the PHP file. So sending data both via GET and POST do not work in this situation.

I am trying to transmit some data from a GUI done in Vue.js to a PHP file using Axios. I tried both with GET and POST parameters but it does not work:

I type the data in this index.php form:

index.php:

<!DOCTYPE HTML>
<HTML>
<head>
    <script src="https://unpkg./vue"></script>
    <script src="https://cdnjs.cloudflare./ajax/libs/axios/0.18.0/axios.js"></script>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn./bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
</head>
<BODY>
    <div id="container" class="container">
        <div>
            <label>First name:</label><br/>
            <input type="text" v-model='newPerson.firstName'>
        </div>
        <div>
            <label>Last name: </label><br/>
            <input type="text" v-model="newPerson.lastName">
        </div>
        <button v-on:click="sendIdentity()">Submit</button>       
    </div>    
    <script src="myjscode.js"></script>
</BODY>
</HTML>

myjscode.js:

When I press the button to submit the data, I see the right output in console.log(response.data):

let vm = new Vue({
    el: "#container",
    data: {
        newPerson: {
            firstName: '',
            lastName: ''
        }
    },
    methods: {
        sendIdentity: function() {
            let personForm = vm.toFormData(vm.newPerson);
            axios.post('phpfile.php', personForm)
                .then( function(response) {
                    console.log(response.data)
                });
        },
        toFormData: function(obj) {
            let formData = new FormData();
            for(let key in obj) {
                formData.append(key, obj[key]);
            }
            return formData;
        }
    }
});

phpfile.php:

On this file, I am rather performing an insertion into a MySQL table, however it never takes effect. I removed the MySQL code and let only what follows, where I notice I always get the message Data not received when I run this file:

<?php
if( isset($_POST['firstName']) && isset($_POST['lastName'])){
   echo $_POST['firstName'];
   echo $_POST['lastName'];      
} else {  
   echo 'Data not received';
}
?>

What am I missing?

Update:

I noticed when I changed the myjscode.js above like ths:

axios.post('phpfile.php?todo=something', ...)

And then I change phpfile.php to

<?php

if( isset($_GET['todo']) ){
   echo $_GET['todo'];
} else {
   echo 'No todo';
}
?>

I am getting No todo always displayed on the PHP file. So sending data both via GET and POST do not work in this situation.

Share Improve this question edited Aug 14, 2018 at 3:03 Billal BEGUERADJ asked Aug 13, 2018 at 18:12 Billal BEGUERADJBillal BEGUERADJ 22.8k45 gold badges123 silver badges140 bronze badges 5
  • 1 what's inside $_POST ? (PHP side) – sheplu Commented Aug 13, 2018 at 18:21
  • I am hoping it is the data in the JS file which are updated by what I type in the input fields of the GUI – Billal BEGUERADJ Commented Aug 13, 2018 at 18:23
  • axios.post('phpfile.php?todo=something', ...) Use a ? instead of / to append to the $_GET array. – JacobW Commented Aug 13, 2018 at 18:50
  • What happens if you console.log vm.newPerson and personForm before the post? Are they both set? – JacobW Commented Aug 13, 2018 at 18:52
  • They get both displayed accordingly @JacobW – Billal BEGUERADJ Commented Aug 13, 2018 at 18:55
Add a ment  | 

2 Answers 2

Reset to default 7

By default axios sends requestBody in json format and with $_POST you only can fetch form-data.

to fetch this json request in php, you need to fetch raw requestBody by typing: file_get_contents('php://input')

also send in json format, without - vm.toFormData(vm.newPerson)

I've created php file on my server to test.

js file content here

php file content here

Your best option might be to set the content-type header so PHP knows what data type to expect.

const options = {
  method: 'POST',
  headers: { 'content-type': 'application/form-data' },
  data: personForm,
  url: 'phpfile.php',
};
axios(options);

Edit:

Create a shared instance of axios for the best results and ease of use.

## Filename /utils/axios.js
const instance = axios.create({
    baseURL: 'https://some-domain./api/ or file.php',
    timeout: 1000,
    headers: {'Content-Type': 'application/form-data'},
    transformRequest: [function (data, headers) {
        // Do whatever you want to transform the data
        let formData = new FormData();
        for(let key in data) {
            formData.append(key, obj[key]);
        }
        return formData;
    }],
});

export default instance;

Then in your ponent file you'd require this instance of /utils/axios.js above like const axios = require('./utils/axios') and now you've got a shared instance with the same config to use throughout. On top of that the above config will use transformRequest to turn your json object into formdata every time so you don't have to do it at the ponent level. Below in your ponents code you'd do:

axios
    .post(jsonObjectofData)
    .then()
    .catch(err => console.log(err));

Edit: Webpackless method

let vm = new Vue({
    el: "#container",
    data: {
        newPerson: {
            firstName: '',
            lastName: ''
        }
    },
    methods: {
        sendIdentity: function() {
            let personForm = vm.toFormData(vm.newPerson);
            const options = {
                method: 'POST',
                headers: { 'content-type': 'application/form-data' },
                data: personForm,
                url: 'phpfile.php',
            };
            axios(options)
                .then( function(response) {
                    console.log(response.data)
                })
                .catch(err => console.log(err);
        },
        toFormData: function(obj) {
            let formData = new FormData();
            for(let key in obj) {
                formData.append(key, obj[key]);
            }
            return formData;
        }
    }
});
发布评论

评论列表(0)

  1. 暂无评论