【问题标题】:form data is showing empty after append追加后表单数据显示为空
【发布时间】:2021-08-22 19:46:57
【问题描述】:

$('#submit2').click(e => {
  e.preventDefault();
  var form_data = new FormData();
  form_data.append('newKey1', 'newValue1');
  form_data.append('newKey2', 'newValue2');
  console.log("data after appended", form_data.get('newKey1'))
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="submit2">See form data in Console</button>

我想在表单数据中添加文件,但我无法追加,所以我尝试添加键和值,但无法在表单数据中追加。

【问题讨论】:

  • 它似乎工作正常。日志消息是“附加 newValue1 后的数据”
  • 我已经更新了您的代码 sn-p,因此您可以看到您的 FormData 设置了值。你不能 console.log 你的 FormData 实例并期望打印整个对象。

标签: javascript jquery forms form-data


【解决方案1】:

你的FormData 很好,你只是不能console.log 它并期望看到内容。

这就是您通常使用FormData 的方式:

document.addEventListener('submit', function (event) {

    event.preventDefault();

    fetch('https://jsonplaceholder.typicode.com/posts', {
        method: 'POST',
        body: new FormData(event.target),
    }).then(function (response) {
        if (response.ok) {
            return response.json();
        }
        return Promise.reject(response);
    }).then(function (data) {
        console.log(data);
    }).catch(function (error) {
        console.warn(error);
    });
});

如果你想记录对象,你需要做这样的事情:

var serializeForm = function (form) {
    var obj = {};
    var formData = new FormData(form);
    for (var key of formData.keys()) {
        obj[key] = formData.get(key);
    }
    return obj;
};

serializeForm(formData)

来源:

【讨论】:

    猜你喜欢
    • 2023-03-14
    • 1970-01-01
    • 1970-01-01
    • 2017-02-09
    • 1970-01-01
    • 2019-05-01
    • 1970-01-01
    • 2021-08-28
    • 2016-05-22
    相关资源
    最近更新 更多