JavaScript window.location没有重定向到不同的页面

时间:2014-12-03 13:26:34

标签: javascript html5 window location

这是我的`index.html

的片段
<div class="maincontainer">
    <h2 id="heading" class="heading"></h2>
    <input type="button" id="resetPassword" class="resetPassword" onclick="resetPassword()" value= "Reset Password" />
    <form method="post" onsubmit="return submitform()">
        <div>
            <input type="password" id="password" name="password" class="patternlock" />
            <input type="submit" value="login"/>
        </div>
    </form>
</div>

这是我在index.html中包含的script.js的片段

function submitform(){
var passwordvalue = document.getElementById("password").value;
var digits = getlength(passwordvalue);
if(digits<5) {
    raiseerror("lengthTooSmall");
}

checkduplicatedigits(passwordvalue);

if (errorraised == false && passwordset == false) {
    localStorage.setItem("passwordvalue", passwordvalue);
    successmessage("patternStored");
}
else if ( errorraised == false && passwordset == true) {
    if (localStorage.getItem("passwordvalue") == passwordvalue) {
        successmessage("screenUnlocked");
    }
    else {
        raiseerror("IncorrectPattern");
    }
}
return true;
};

function successmessage(successcode) {
    if(successcode == "screenUnlocked") {
        alert("You have unlocked the screen!");
        window.location = "./welcome.html";  //bug to be fixed
    }
    if (successcode == "patternStored") {
        alert("Your pattern is stored. Thanks.");
        passwordset = true; 
    }
    if (successcode == "resetSuccess") {
        alert("Pattern Reset Success!");
    }
    location.reload();
};

此时,只要触发successcode ==“screenUnlocked”,我就能收到提醒信息

alert("You have unlocked the screen!");

但下一行

window.location = "./welcome.html";

无效。

为什么不在这种情况下工作? window.location是否有特定要求可以使用?如果是,请说明。

Google Chrome 39.0.2171.71 上检查此代码。我已经检查了我的控制台错误,但不是。只有少数警告,但它们与此无关。

还是任何其他功能使用纯Javascript进行重定向?如果是,请说明。

如果需要任何进一步的信息,请发表评论。

3 个答案:

答案 0 :(得分:1)

首先,这不安全所以我希望这不是真正的保护。

它失败的原因是你有window.location和表单提交的竞争条件。表单正在提交,因为您没有取消表单提交。

您需要在验证函数结束时返回false,而不是true。

答案 1 :(得分:0)

替换

successmessage("screenUnlocked");

通过

successmessage("screenUnlocked");
return false;

答案 2 :(得分:-1)

我认为你需要使用

window.location.href = "./welcome.html";

这个问题最好在这里得到解答

How to redirect to another webpage in JavaScript/jQuery?