简体   繁体   English

在javascript函数中添加<%%>将在页面加载时强制执行?

[英]Adding <%%> inside a javascript function will be executed by force on page load?

i have the following javascript function: 我有以下javascript函数:

        function redirect() {
        window.setTimeout(function () { <% Response.Redirect("~/Pages/ExecrcisePlan.aspx"); %> }, 2000);
    }

I wanted to call this function from inside my asp.net page but it's executing when i enter the page and redirecting me without even calling the function, and event when i commented that line same thing happened, i know i can use other javascript alternative but was curios why it didn't work and if there is anyway to make it work ? 我想从我的asp.net页面调用这个函数,但它正在执行当我进入页面并重定向我甚至没有调用函数,并且事件当我评论该行同样的事情发生时,我知道我可以使用其他javascript替代但好奇为什么它不起作用,如果有任何方法使它工作?

When you use <% %> blocks inside an aspx or cshtml page. 在aspx或cshtml页面中使用<%%>块时。 The code get evaluated immediately on page creation, because they are server side code blocks. 在页面创建时立即评估代码,因为它们是服务器端代码块。 You can call it by using an ASP.Net AJAX Timer control instead of using pure javascript. 您可以使用ASP.Net AJAX Timer控件而不是使用纯JavaScript来调用它。

Another alternative would be using an javascript redirection method like location.href, and then use a block <% Response.Write(url) %> to output the URL you want. 另一种方法是使用像location.href这样的javascript重定向方法,然后使用块<%Response.Write(url)%>来输出所需的URL。

What you want to do is: 你想要做的是:

redirect();

function redirect() {
  var x = setTimeout(function() {
  window.location.replace(<% Url.Content("~/Pages/ExecrcisePlan.aspx"); %>);
  }, 2000);
}

http://jsbin.com/aQaLuVA/1/ http://jsbin.com/aQaLuVA/1/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM