【问题标题】:How to run JavaScript or jQuery script before page is rendered如何在页面呈现之前运行 JavaScript 或 jQuery 脚本
【发布时间】:2011-02-08 16:52:30
【问题描述】:

如何在页面呈现之前运行 JavaScript 或 jQuery 脚本?

具体来说,我想检查某些 cookie 是否存在。

如果 cookie 不存在,我不想显示页面内容,而是立即重定向到身份验证页面。

目前,页面内容已加载并呈现,之后浏览器重定向到认证页面。

我试过了:

<body onload="checkCookies()">
...
</body>

还有:

<head>
<script type="text/javascript">checkCookies();</script>
...
</head>

在这两种情况下,都会加载相关页面,然后检查 cookie。

如何使用 JavaScript(或 jQuery)并在加载页面的其余部分之前进行 cookie 检查?

【问题讨论】:

    标签: javascript jquery http cookies


    【解决方案1】:

    不要使用 Javascript 进行身份验证。逃避非常容易——您只需要关闭 Javascript。在呈现页面之前使用服务器端代码进行身份验证检查。

    【讨论】:

      【解决方案2】:

      只需像下面这样使用它:

      <script type="text/javascript">
         if(checkCookie()){
           document.location="./configure/network.xml"
         }
      </script>
      

      并将其放在脚本的顶部。它对我有用

      【讨论】:

        【解决方案3】:

        使用服务器端脚本进行身份验证。 如果您想使用 javascript 检查 cookie,请使用此

        function checkCookie()
        {
        var username=getCookie("username");
          if (username!=null && username!="")
          {
          alert("Welcome again " + username);
          }
        else
          {
          username=prompt("Please enter your name:","");
          if (username!=null && username!="")
            {
            setCookie("username",username,365);
            }
          }
        }
        

        【讨论】:

          【解决方案4】:

          看看 -->

          您可以使用页面的预渲染事件。

          protected override void OnPreRender(EventArgs e)
          {
              base.OnPreRender(e);
              //If cookie doesn't exist redirect to the authentication page.
              if (Request.Cookies["UserName"] == null)
              {
                  //redirects to the authentication page.
              }
          }
          

          【讨论】:

            猜你喜欢
            • 2017-06-29
            • 1970-01-01
            • 2016-12-23
            • 2021-07-04
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2017-01-13
            相关资源
            最近更新 更多