表单提交后刷新页面,在控制台输出数据
时间: 2023-12-19 12:07:31 浏览: 94
可以通过以下步骤实现:
1. 监听表单的提交事件,使用 `addEventListener` 方法。
2. 在事件处理函数中阻止表单默认的提交行为,使用 `preventDefault` 方法。
3. 获取表单中的数据,可以使用 `FormData` 对象。
4. 发送数据到后端,使用 `fetch` 方法。
5. 在 `fetch` 方法的回调函数中,刷新页面并输出数据。
以下是示例代码:
```html
<form id="myForm">
<label for="name">Name:</label>
<input type="text" id="name" name="name"><br><br>
<label for="email">Email:</label>
<input type="email" id="email" name="email"><br><br>
<input type="submit" value="Submit">
</form>
```
```javascript
const form = document.querySelector('#myForm');
form.addEventListener('submit', function(event) {
event.preventDefault(); // 阻止表单默认的提交行为
const formData = new FormData(form); // 获取表单中的数据
fetch('/submit', {
method: 'POST',
body: formData
})
.then(response => response.json())
.then(data => {
console.log(data); // 输出数据到控制台
location.reload(); // 刷新页面
})
.catch(error => console.error(error));
});
```
注意,以上代码中的 `'/submit'` 是后端接口的 URL,需要根据实际情况进行修改。另外,后端需要返回 JSON 格式的数据,才能在前端通过 `response.json()` 方法获取到数据。
阅读全文
相关推荐


















