使用 axios post 表单 symfony 访问 vue js 数据

Access vue js data with axios post form symfony

您好,我正在尝试通过 axios 从 symfony 后端访问 vue.js 数据数组。这是我的代码。

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'];
    .......
}

但不幸的是,我得到的是没有名为 brand 的索引 :(。如果有人可以帮助我,那就太好了。我想我需要找到一种方法来发送完整的数据数组到后端 我可以这样发送数据,

axios.post('http://localhost:81/lnt/public/member/car_result', {brand: this.brand})

将axios代码写成

 axios.post('http://localhost:81/lnt/public/member/car_result', this.data)
                            .then(function (response) {

这段代码有两个问题。

1 this.data 未定义

您的数据如下:

{data: this.data}

你可能希望有结构

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

但是它不起作用,因为 this.data 不是 Vue 实例的数据 属性。它看起来很神奇,但是调用 this['property'] 你要求 Vue 获得 data 的反应 属性 的值,所以如果你想获得 brand 你应该输入 this.brand.

2 您的数据模型在客户端和服务器上不同

事件如果json的这种结构可以实现然后在Symfony的控制器中你询问

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

但实际上,您的请求在第一层没有 'brand' 键。您应该将后端代码替换为

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

或将您的客户端代码代码粘贴请求正文替换为

{brand: this.brand}