rom*_*n m 47 javascript asp.net
我需要运行一个JavaScript函数onLoad(),但只有在第一次加载页面时才会这样做(即不是回发的结果).
基本上,我需要在JavaScript中检查IsPostBack.
谢谢.
Jas*_*ing 67
服务器端,写:
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);
}
Run Code Online (Sandbox Code Playgroud)
然后,在为onLoad运行的脚本中,检查该变量是否存在:
if(isPostBack) {
// do your thing
}
Run Code Online (Sandbox Code Playgroud)
你不需要设置变量,就像Jonathan的解决方案一样.客户端if语句将正常工作,因为"isPostBack"变量将是未定义的,在if语句中计算为false.
小智 26
有一种更简单的方法,不涉及在后面的代码中写任何东西:只需将此行添加到您的javascript:
if(<%=(Not Page.IsPostBack).ToString().ToLower()%>){//Your JavaScript goodies here}
Run Code Online (Sandbox Code Playgroud)
要么
if(<%=(Page.IsPostBack).ToString().ToLower()%>){//Your JavaScript goodies here}
Run Code Online (Sandbox Code Playgroud)
小智 12
你好试试以下......
function pageLoad (sender, args) {
alert (args._isPartialLoad);
}
Run Code Online (Sandbox Code Playgroud)
结果是一个布尔值
该解决方案对我不起作用,我不得不对其进行调整:
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);
}
Run Code Online (Sandbox Code Playgroud)
希望这可以帮助。