代码之家  ›  专栏  ›  技术社区  ›  tohhy

如何使用Fetch API从表单中检索和发送数据?

  •  1
  • tohhy  · 技术社区  · 7 年前

    <form action="file.php" method="post">
        <input name="formName" type="text" />
        <input name="formEmail" type="email" />
        <input name="formSubmit" type="submit" value="Submit Me!" />
    </form>
    

    所以,如何使用Fetch API来获取这些值并将其发送到文件。使用ajax的php文件?

    1 回复  |  直到 7 年前
        1
  •  5
  •   Muthu Kumaran    7 年前

    使用 Fetch API

    function submitForm(e, form){
        e.preventDefault();
        
        fetch('file.php', {
          method: 'post',
          body: JSON.stringify({name: form.formName.value, email: form.formEmail.value})
        }).then(function(response) {
          return response.json();
        }).then(function(data) {
          //Success code goes here
          alert('form submited')
        }).catch(function(err) {
          //Failure
          alert('Error')
        });
    }
    <form action="file.php" method="post" onsubmit="submitForm(event, this)">
        <input name="formName" type="text" />
        <input name="formEmail" type="email" />
        <input name="formSubmit" type="submit" value="Submit Me!" />
    </form>