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

时间:2017-07-28 09:44:35

标签: javascript php html 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>

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

1 个答案:

答案 0 :(得分:2)

使用Fetch API

&#13;
&#13;
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')
    });
}
&#13;
<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>
&#13;
&#13;
&#13;

相关问题