AJAX 提交表单,页面为什么会刷新?
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>TTT</title>
</head>
<body>
<form id="f" method="get">
<input type="text" placeholder="A">
<button type="submit">B</button>
</form>
<script>
document.getElementById('f').onsubmit = function (e) {
console.log(e);
const xhr = new XMLHttpRequest();
xhr.open('get', '', true);
xhr.send();
};
</script>
</body>
</html>
上面这段简短的代码,点击按钮,预期应该是在 console
里打印出提交事件,然后页面不刷新,结果TM每次点击按钮整个页面都刷新一次————
已尝试方法
在 onsubmit
函数最后加上 return false
可以做到异步提交,不刷新网页。
但是
但是,我很确定我以前实现的异步提交从来都没用过 return false
,不知道为什么这次突然就不行了,有没有大神能够回答?
附上之前没加 return false
仍然成功的代码————
function post_tab() {
// 提交标签打印数量
document.getElementById('work_form').onsubmit = function (e) {
e.preventDefault();
const xhr = new XMLHttpRequest(),
f = e.target,
formData = new FormData(f),
log = $('#print_log');
xhr.open('POST', f.action, true);
xhr.responseType = 'json';
xhr.onreadystatechange = function () {
if(xhr.readyState === 4 && xhr.status === 200){
const data = xhr.response;
console.log(data);
print_tab(data['qrs'], log[0]);
log.scrollTop(log[0].scrollHeight - log.height());
input_clean('input_qr');
}
};
xhr.send(formData);
}
}
该函数 post_tab
使用 onclick
绑定在提交按钮上————
<button class="btn btn-success form-control" onclick="post_tab()">开始打印</button>
e.preventDefault();
和return false;
等效前者为阻止默认事件。