我有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文件?
答案 0 :(得分:2)
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;