【问题标题】:How should i format my JSON in Vue using Axios to look like this?我应该如何使用 Axios 在 Vue 中格式化我的 JSON,使其看起来像这样?
【发布时间】:2020-07-01 01:33:49
【问题描述】:

我花了几个小时试图弄清楚如何在 Vue.js 中格式化我的 JSON 以便以这种方式发送:

目前我正在尝试使用 FormData() 对象,但结果仍然只是:

我的函数如下所示:

register () {
        var bodyFormData = new FormData();
        bodyFormData.append('firstname', 'Coca');
        bodyFormData.append('lastname', 'Cola')
        console.log(jsonData)
        axios({
          method: 'post',
          url: 'backend/index.php?action=createUser',
          data: bodyFormData,
          headers: {'Content-Type': 'multipart/form-data' }
          })
          .then(function (response) {
              //handle success
              console.log(response);
          })
          .catch(function (response) {
              //handle error
              console.log(response);
          });
      }

我已经通过jQuery AJAX调用实现了第一张图片的结果,在Vue中使用Axios也可以吗?

【问题讨论】:

    标签: javascript json ajax vue.js axios


    【解决方案1】:

    您可以使用JSON.stringify 方法并将您的对象附加到您的表单数据中。

    bodyFormData.append('data', JSON.stringify(jsonData));
    

    【讨论】:

      【解决方案2】:

      您明确使用Content-Type: multipart/form-data 并为您的data 参数发送表单数据。要发送 JSON,请将 data 设置为您要序列化为 JSON 的对象,并使用 application/json 作为您的 content-type。

      async register () {
        try {
          const response = await axios({
            method: 'post',
            url: 'backend/index.php?action=createUser',
            data: { firstname: 'Coca', lastname: 'Cola' },
            headers: {'Content-Type': 'application/json' }
          });
          //handle success
          console.log(response);
        } catch (err) {
          //handle error
          console.log(err);
        }
      }
      

      【讨论】:

      • 如果您想发送带有 JSON 数据属性的表单数据,而不仅仅是在您的帖子正文中发送 JSON,那么@ZdravkoPernikov 有正确的答案。
      【解决方案3】:

      感谢您的回答,我实际上必须制作一个 FormData 并用字符串化的 JSON 数据填充它。

      【讨论】:

        猜你喜欢
        • 2020-05-18
        • 2020-10-15
        • 2020-07-18
        • 2023-03-03
        • 1970-01-01
        • 2011-04-09
        • 1970-01-01
        • 1970-01-01
        • 2021-04-29
        相关资源
        最近更新 更多