js页面重定向跳转被阻拦

JavaScript015

js页面重定向跳转被阻拦,第1张

常规页面location.href跳转被阻止时,不涉及前端部分。

也有可能是浏览器本身对于http和https的证书验证拦截,并非bug。

以下为https在大部分浏览器标识。

部分浏览器会因以下原因阻止页面的重定向。

OnClientClick="window.DestinationUrl()return

false"

或者直接在按钮的后台代码里面写Response.Redirect("百度url")

这个原因是响应时间的问题,因为你的服务器按钮控件是先响应OnClientClick,然后再自动PostBack,然后再回复页面给浏览器。因此,当你需要进行location跳转的时候,这个时候已进入到了后台,后台解析了当前页面给浏览器,结果又回来了。

加入return

false的目的就是告诉OnClientClick,页面阻止你向后台提交。

至于为什么用Html控件成功,原因是html控件是不会自动PostBack的,而Button会自动PostBack。你这是一个纯的前端动作,没必要用到后台

<!DOCTYPE html>

<html lang="en">

<head>

    <meta charset="UTF-8">

    <title>Document</title>

    <head>

        <script type="text/javascript">

            function login() {

                var username = document.getElementById("username").value

                var password = document.getElementById("password").value

                if (username == "a" && password == "123") {

                    alert("登录成功!")

                    location.href = "user.html"

                } else {

                    alert("登录失败!")

                    myform.onsubmit = new Function("return false")

                }

            }

        </script>

    </head>

    <body>

        <div class="container">

            <section id="content">

                <form action="" method="get" id="myform">

                    <div>

                        <input type="text" placeholder="用户名" required="" id="username" />

                    </div>

                    <div>

                        <input type="password" placeholder="密码" required="" id="password" />

                    </div>

                    <div>

                        <input type="submit" id="submit" value="登  录" onclick=" login()" />

                    </div>

                </form>

            </section>

        </div>

    </body>

</html>