<!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>
return false
仍然能够异步提交不刷新网页呢? 1 CoderEQ 2018-10-16 11:39:10 +08:00 第一段代码有<button type="submit">B</button> type 属性表示属于 form 表单元素。第二段<button class="btn btn-success form-control" Onclick="post_tab()">开始打印</button> 仅仅是一个 button,跟 form 无关,所以不触发 |
2 no502zhang 2018-10-16 11:41:11 +08:00 form 中的 button 为 submit, 默认就会提交 form form 的 action 不写, 默认就是当前页 |
3 simadad OP @CoderEQ 第二段省略了 `type`,chrome 的缺省值就是 submit,我刚刚测试了一下,把第二段的 `type="submit"` 加上,仍然不触发 |
4 iNaru 2018-10-16 13:39:37 +08:00 ![]() e.preventDefault(); 阻止了浏览器的提交这个默认行为 |