要使用 fetch
函数和 async/await
语法进行 POST 请求并在表单提交时处理响应,你可以按照以下步骤操作:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Fetch POST Example</title>
</head>
<body>
<form id="myForm">
<input type="text" name="username" placeholder="Username">
<input type="password" name="password" placeholder="Password">
<button type="submit">Submit</button>
</form>
<script src="./index.js"></script>
</body>
</html>
index.js
)包含以下代码:document.addEventListener('DOMContentLoaded', async () => {
const form = document.getElementById('myForm');
form.addEventListener('submit', async (event) => {
event.preventDefault(); // 阻止表单默认提交行为
const formData = new FormData(form);
const response = await fetch('https://your-api-url.com/submit', {
method: 'POST',
body: formData
});
if (response.ok) {
const data = await response.json();
console.log('Success:', data);
} else {
console.error('Error:', response.statusText);
}
});
});
这里的关键点是:
async/await
语法处理异步操作。FormData
类型的对象来获取表单中的数据。fetch()
函数发送 POST 请求,并将 method
设置为 'POST'
。await
关键字等待服务器响应,然后根据响应结果进行处理。请注意,你需要将示例代码中的 'https://your-api-url.com/submit'
替换为你自己的 API URL。
领取专属 10元无门槛券
手把手带您无忧上云