如何在JavaScript中检查IsPostBack?
我需要运行JavaScript函数onLoad(),但只有在页面首次加载时(即不是回发的结果)才可以执行。
基本上,我需要在JavaScript中检查IsPostBack。
谢谢你。
解决方案
回答
我们可以在页面上放置一个隐藏的输入,并在页面加载后为它提供一个值。然后,我们可以检查该字段,如果它在发布数据中,则为回发,否则为不。
有两种解决方案使用发布的服务器端代码(特定于ASP.NET)作为响应。我认为值得指出的是,此解决方案与技术无关,因为它仅使用客户端功能,所有主要浏览器都提供该功能。
回答
我们可以创建一个值为0的隐藏文本框。将onLoad()代码放在if块中,以检查以确保该隐藏文本框值为0。如果执行该代码,则将文本框值设置为1.
回答
这是一种方法(将其放入Page_Load中):
if (this.IsPostBack) { Page.ClientScript.RegisterStartupScript(this.GetType(),"PostbackKey","<script type='text/javascript'>var isPostBack = true;</script>"); }
然后只需在JS中检查该变量即可。
回答
服务器端,写:
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运行的脚本中,检查该变量是否存在:
if(isPostBack) { // do your thing }
我们实际上不需要像Jonathan的解决方案那样设置其他变量。客户端的if语句将正常工作,因为" isPostBack"变量将是未定义的,在该if语句中该变量的值为false。
回答
这里有很多选择。
对于纯JS解决方案,让页面提交给自己,但是使用其他URL参数(mypage.html?postback = true),我们可以使用window.location.href获取页面url,并使用split或者regex解析为寻找变数。
假设我们发送回某种脚本语言来处理该页面(php / perl / asp / cf等),最简单的方法是让它们在页面中回显一行JavaScript,并设置一个变量:
<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():"> ...
回答
还有一种更简单的方法,它不需要在背后的代码中编写任何内容:只需将以下行添加到javascript中:
if(<%=(Not Page.IsPostBack).ToString().ToLower()%>){//Your JavaScript goodies here}
或者
if(<%=(Page.IsPostBack).ToString().ToLower()%>){//Your JavaScript goodies here}
回答
该解决方案对我不起作用,我不得不对其进行调整:
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); }
希望这可以帮助。
回答
尝试一下,在此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; } }