如何使用 Fetch API 从表单中检索和发送数据?
How to use Fetch API to retrieve and send data from form?
我有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 文件?
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>
我有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 文件?
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>