【问题标题】:Why the FormData() constructor does not work [duplicate]为什么 FormData() 构造函数不起作用[重复]
【发布时间】:2023-03-17 05:05:01
【问题描述】:

我有这个登录代码。 当我调试代码时,我检查 FormData() 构造函数没有返回任何东西,它是空的。我究竟做错了什么? formLog 常量确实会收集表单数据,但在将其传递给 FormData() 构造函数后,返回的对象为空

<form id="login" method="post" enctype="multipart/form-data" name="login">
    <input type="email" name="email" placeholder="Tu email">
    <br><br>
    <input type="password" name="password" placeholder="Tu contraseña">
    <br><br>
    <input type="submit" value="Login">
</form>

<script type="text/javascript">
    const formLog = document.querySelector('#login')
    //Creamos un objeto con los datos del formulario

    // AL formLog le agregamos un evento 
    formLog.addEventListener('submit',event =>{
        event.preventDefault()
        const data = new FormData(formLog)       
        fetch('/api/signin',{
            method:'POST',
            body: data,
        })
        .then(res => {
            res.json()
        })
        .then(resData => {
            localStorage.setItem('token', resData.token)
        })
    })
</script>

【问题讨论】:

  • 使用this,你会看到data确实包含表单数据。您还可以在控制台中查看 XHR 参数,它还会显示名称和值。

标签: javascript fetch form-data


【解决方案1】:

使用spread syntax 将从您的FormData 对象中获取所有值。然后使用Array#reducedestructuring 将所有内容组织在一个简单的对象中。

const form = document.getElementById("login");

form.addEventListener("submit", function(e){
  e.preventDefault();
  
  const data = [...new FormData(this)]
  .reduce((a,[key,value])=>{
    a[key] = value;
    return a;
  }, {});
  
  console.log(data);
});
<form id="login" method="post" enctype="multipart/form-data" name="login">
    <input type="email" name="email" placeholder="Tu email" value="test@test.com">
    <br><br>
    <input type="password" name="password" placeholder="Tu contraseña" value="some password">
    <br><br>
    <input type="submit" value="Login">
</form>

【讨论】:

  • @JoséEspejoRoig 没问题。不要忘记标记为正确答案。干杯。
猜你喜欢
  • 2015-11-02
  • 2013-08-24
  • 2022-07-29
  • 2012-12-18
  • 1970-01-01
  • 2022-01-04
  • 1970-01-01
  • 2014-05-10
  • 1970-01-01
相关资源
最近更新 更多