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

toh*_*hhy 1 html javascript php ajax fetch-api

我有 html 表单:

<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>
Run Code Online (Sandbox Code Playgroud)

那么如何使用 Fetch API 来获取这些值并使用 ajax 将它们发送到 file.php 文件呢?

Mut*_*ran 5

使用获取 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')
    });
}
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)