我如何检查JavaScript中的IsPostBack?

我需要运行一个JavaScript函数onLoad(),但只有在第一次加载的页面(即不是回发的结果)时才能执行。

基本上,我需要在JavaScript中检查IsPostBack。

谢谢。

服务器端,写:

if(IsPostBack) { // NOTE: the following uses an overload of RegisterClientScriptBlock() // that will surround our string with the needed script tags ClientScript.RegisterClientScriptBlock(GetType(), "IsPostBack", "var isPostBack = true;", true); } 

然后,在为onLoad运行的脚本中,检查是否存在该variables:

 if(isPostBack) { // do your thing } 

您不需要设置variables,如乔纳森的解决scheme。 客户端的if语句将正常工作,因为“isPostBack”variables将是未定义的,在if语句中,其计算结果为false。

有一个更简单的方法,不涉及在后面的代码中写任何东西:只需将此行添加到您的javascript:

 if(<%=(Not Page.IsPostBack).ToString().ToLower()%>){//Your JavaScript goodies here} 

要么

 if(<%=(Page.IsPostBack).ToString().ToLower()%>){//Your JavaScript goodies here} 

嗨尝试以下…

 function pageLoad (sender, args) { alert (args._isPartialLoad); } 

结果是一个布尔值

解决scheme不适合我,我不得不适应它:

 protected void Page_Load(object sender, EventArgs e) { string script; if (IsPostBack) { script = "var isPostBack = true;"; } else { script = "var isPostBack = false;"; } Page.ClientScript.RegisterStartupScript(GetType(), "IsPostBack", script, true); } 

希望这可以帮助。

您可以在页面上放置一个隐藏的input,并在页面加载后给它一个值。 然后你可以检查该字段,如果是在发布数据,这是一个回传,否则它不是。

有两种解决scheme使用服务器端代码(特定于ASP.NET)作为响应发布。 我认为值得指出的是,这个解决scheme是技术无关的,因为它只使用客户端function,这在所有主stream浏览器中都是可用的。

试试这个,在这个JS中,我们可以检查它是否回发,并相应地在相应的循环中进行操作。

  window.onload = isPostBack; function isPostBack() { if (!document.getElementById('clientSideIsPostBack')) { return false; } if (document.getElementById('clientSideIsPostBack').value == 'Y') { ***// DO ALL POST BACK RELATED WORK HERE*** return true; } else { ***// DO ALL INITIAL LOAD RELATED WORK HERE*** return false; } } 

您可以创build一个值为0的隐藏文本框。将onLoad()代码放置在if块中,以检查是否隐藏文本框值为0.如果它是执行代码并将文本框值设置为1。

这里有很多select。

对于一个纯粹的JS解决scheme,让你的页面提交给自己,但增加了URL参数(mypage.html?postback = true) – 然后你可以得到页面URL与window.location.href,并parsing,使用拆分或正则expression式寻找你的variables。

假设你发回某种脚本语言来处理页面(php / perl / asp / cf et.al),那么容易得多的是让它们在页面中设置一个variables:

 <html> <?php if ($_POST['myVar']) { //postback echo '<script>var postingBack = true;</script>'; //Do other processing } else { echo '<script>var postingBack = false;</script>' } ?> <script> function myLoader() { if (postingBack == false) { //Do stuff } } <body onLoad="myLoader():"> ... 

这是一种方式(把它放在Page_Load中):

 if (this.IsPostBack) { Page.ClientScript.RegisterStartupScript(this.GetType(),"PostbackKey","<script type='text/javascript'>var isPostBack = true;</script>"); } 

然后在JS中检查这个variables。

创build一个全局variables并应用该值

 <script> var isPostBack = <%=Convert.ToString(Page.IsPostBack).ToLower()%>; </script> 

那么你可以从其他地方引用它