【问题标题】:Access vue js data with axios post form symfony用axios post form symfony访问vue js数据
【发布时间】:2019-05-12 09:20:50
【问题描述】:

您好,我正在尝试通过 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'];
    .......
}

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

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

【问题讨论】:

  • 您正在尝试获取数据,但您发送的是发布请求,而不是获取请求。如果您只返回一个字符串会怎样 - 您可以 console.log 这个响应吗?
  • console.log(this.data);我这样做了,得到了未定义的输出

标签: vue.js axios symfony4


【解决方案1】:

把axios代码写成

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

【讨论】:

  • 真的很抱歉兄弟,但我仍然是 null :(
  • 尝试使用邮递员获取数据。这将告诉你你的代码是否工作
【解决方案2】:

这段代码有两个问题。

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 = json_decode($request->getContent(), true)['data']['brand'];

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

{brand: this.brand}

【讨论】:

    猜你喜欢
    • 2017-12-26
    • 2020-07-18
    • 2020-10-16
    • 1970-01-01
    • 2021-01-04
    • 2019-05-17
    • 2019-11-05
    • 2018-03-22
    • 2020-05-28
    相关资源
    最近更新 更多