DIV CSS 佈局教程網

用 JavaScript 實作使用者登入與自動跳轉的完整流程
編輯:JavaScript基礎知識     

這篇文章示範一個簡單的登入流程:使用者在登入頁輸入帳號 pwd、密碼 123,驗證通過後會跳到第二個頁面;該頁面停留數秒後,再自動跳轉到第三個(成功)頁面。整個範例由三個檔案組成。

login.html(登入頁)

<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8">
<script type="text/javascript">
    // 進行檢查
    function check(){
        if ($("username").value == "pwd" && $("pwd").value == "123") {
            return true;
        } else {
            $("username").value = "";
            $("pwd").value = "";
            return false;
        }
    }
    // 獲取文檔對象
    function $(id){
        return document.getElementById(id);
    }
</script>
</head>
<body>
<form action="ok.html">
u: <input type="text" id="username" /><br/>
p: <input type="password" id="pwd" /><br/>
<input type="submit" value="提交" onclick="return check()"/>
</form>
</body>
</html>

這裡自訂了一個 $ 函式作為 getElementById 的簡寫,方便後續取用元素。按下提交時會先呼叫 check() 驗證帳密,通過才允許送出表單。

ok.html(跳轉提示頁)

<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8">
<script type="text/javascript">
    // 跳轉到指定頁面
    function tiao(){
        clearInterval(myInterval);
        window.open("success.html", "_self");
    }
    // 設置 5 秒跳轉
    setTimeout("tiao()", 5000);

    // 改變秒數
    function changeSec(){
        $("myspan").innerText = parseInt($("myspan").innerText) - 1;
    }
    var myInterval = setInterval("changeSec()", 1000);

    // 獲取對象
    function $(id){
        return document.getElementById(id);
    }
</script>
</head>
<body>
登錄成功 <span id="myspan">5</span> 秒後自動跳轉
</body>
</html>

這個頁面透過 setTimeout 設定 5 秒後跳轉,同時用 setInterval 每秒遞減頁面上顯示的倒數秒數,讓使用者有明確的等待提示。

success.html(成功頁)

<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8">
<script type="text/javascript">
</script>
</head>
<body>
歡迎.......
</body>
</html>

這是最終的登入成功頁面。整體來說,這個範例把「表單驗證」、「定時跳轉」與「倒數計時」三個常見技巧結合在一起,很適合當作入門練習。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved