如何讓form 表單提交數據後,頁面不跳轉不刷新?(已解決)

思路:
需要一個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>&nbsp;<button type="reset">重置</button>
    </form>
    <script>
        document.querySelector('button').onclick=()=>{
            console.log("已經成功提交"+document.querySelector('input').value);
        }
    </script>
</body>
</html>

在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章