思路:
需要一個iframe標籤做替罪羊,form點擊提交後數據提交到iframe裏面,當什麼都沒發生一樣,先把寫好的iframe標籤隱藏起來,給form綁定屬性target爲和iframe的name一模一樣的值,當點擊button進行提交後,就會提交到iframe框裏面,這樣就不會重新打開一個新頁面且成功提交數據
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
iframe{
display: none;
}
</style>
</head>
<body>
<iframe src="" frameborder="0" name="iframeName"></iframe>
<form action=" " target="iframeName">
用戶名: <input type="text" placeholder="請輸入用戶名">
<button>提交</button> <button type="reset">重置</button>
</form>
<script>
document.querySelector('button').onclick=()=>{
console.log("已經成功提交"+document.querySelector('input').value);
}
</script>
</body>
</html>