代码之家  ›  专栏  ›  技术社区  ›  vimuth

使用axios post form symfony访问vue js数据

  •  1
  • vimuth  · 技术社区  · 7 年前

    var vm = new Vue({
                    el: '#el',
                    delimiters: ["[[", "]]"],
                    data: {
                        brand: 0,
                        model: 0,
                        country: "europe",
                    },
                    created: function () {
                    },
                    updated: function () {
                        axios.post('http://localhost:81/lnt/public/member/car_result', {data: this.data})
                                .then(function (response) {
    
                                });
                    }
                });
    

    这是我的symfony代码,

    /**
     * @Route("/car_result", name="car_result", methods="POST")
     */
    public function carResult(Request $request) {
        $data = $request->getContent();
        $data = json_decode($data, true);
    
        $brand = $data['brand'];
        .......
    }
    

    但不幸的是,我得到的是没有所谓的品牌指数:(。如果有人能在这方面帮助我,那就太好了。 我想我需要找到一种方法将完整的数据数组发送到后端 我可以发送这样的数据,

    axios.post('http://localhost:81/lnt/public/member/car_result', {brand: this.brand})
    
    2 回复  |  直到 7 年前
        1
  •  1
  •   Mak Sr    7 年前

    将axios代码编写为

     axios.post('http://localhost:81/lnt/public/member/car_result', this.data)
                                .then(function (response) {
    
        2
  •  1
  •   Community Mohan Dere    6 年前

    这段代码有两个问题。

    1. this.data

    您的数据如下:

    {data: this.data}
    

    你可能希望有一个结构

    {
        data: {
            brand: 0,
            model: 0,
            country: "europe",
        }
    }
    

    这是数据 不是的数据属性 Vue 例子这看起来很神奇,但是 this['property'] 您要求Vue确定的是 data ,所以如果你想 brand 你应该打字 this.brand .

    json 然后在你询问的Symfony控制器中实现

    $brand = json_decode($request->getContent(), true)['brand'];
    

    但实际上,您的请求在第一级没有“品牌”键。您应该将后端代码替换为

    $brand = json_decode($request->getContent(), true)['data']['brand'];
    

    {brand: this.brand}
    
    推荐文章