2016-11-21 109 views
1

我試圖在成功登錄後直接指向另一個文件。但是,在登錄成功警告顯示後,似乎沒有能夠轉到b.html。它似乎仍然在同一頁面。我曾嘗試document.location.hrefwindow.location.replace但它似乎沒有工作jQuery重定向到另一個文件

<script> 
    window.onload = function() { 
     document.addEventListener("deviceready", init, false); 
    } 

    function init() { 
     document.getElementById("btnSave").addEventListener("click", saveData, false); 
     document.getElementById("btnGet").addEventListener("click", getData, false); 
    } 

    function getData() { 
     var email1 = document.getElementById("email1").value; 
     var pass1 = document.getElementById("password1").value; 
     var email2 = window.localStorage.getItem("email"); 
     var pass2 = window.localStorage.getItem("pass"); 
     if (email1 == email2 && pass1 == pass2) { 
      alert("Login successfully"); 
      window.location.href = "/b.html"; 
     } else { 
      alert("Invalid login credentials"); 
     } 
    } 
</script> 
<form class="login-form"> 
    <input type="email" id="email1" name="email1" placeholder="Email Address" required/> 
    <input type="password" id="password1" name="password1" placeholder="Password" required/> 
    <button id="btnGet" type="submit" name="submit">Login</button> 
</form> 
+1

使用完整的URL與域和檢查。 http://stackoverflow.com/questions/6109527/window-location-href-not-working-in-form-onsubmit – Cruzer

+0

1.不要在表單中調用任何'name =「submit」'。 2.如果提交表單,則離開頁面,腳本可能沒有時間執行或表單不會向服務器發送任何內容。而是讓表單動作重定向。 3.在location.href中使用完全限定的URL - PS:如果需要在處理程序中執行JavaScript,請將按鈕更改爲鍵入=「按鈕」 - otherise在服務器上執行操作或取消提交 – mplungjan

+0

但如果我有表單動作重定向,即使它的失敗登錄,它仍然會將用戶引導到該頁面? – fypforstack

回答

4

之所以您重定向不起作用的是,點擊Login按鈕提交表單。這是Web瀏覽器的正常行爲。在你的情況下,你需要防止這種默認行爲。

使用jQuery,你可以做這樣的:既然你不是在你的代碼中使用jQuery在所有

$('form.login-form').submit((e) => { 
    e.preventDefault(); 
}); 

,你可能有興趣在這樣一個版本:

form.addEventListener('submit', e => { 
    e.preventDefault(); 
}); 

另一種解決方案是不要將type="submit"屬性添加到登錄按鈕。

但是,您可以做的最好的(以及網絡用戶習慣的)是在提交表單後重定向用戶。那麼不僅當用戶點擊該按鈕,但是這將工作時,他按下ENTER以及等

那麼你的代碼應該是這樣的:

(() => { 
    let form; 

    function init() { 
     form = document.querySelector('login-form'); 

     if (!form) { 
      throw new ElementNotFoundException(); 
     } 

     form.addEventListener('submit', onSubmitHandler); 
    } 

    function onSubmitHandler(e) { 
     e.preventDefault(); 

     // get values, validate... 

     window.location.href = 'b.html'; 
    } 

    init(); 
}); 
1

也許位置HREF不正確writen,請更換window.location.href = "/b.html";window.location.href = "b.html";

+0

以前試過,也不管用 – fypforstack

+0

你確定b.html在你的html所在的同一目錄下嗎? –

+0

是的,我已經嘗試過頭(),它的工作原理,不使用這個jQuery雖然 – fypforstack