简体   繁体   中英

Is there such a thing as 'if (!Page.IsPostBack)' in jQuery or javascript?

有没有办法检测页面何时加载它是回发还是只是页面加载?

JavaScript has no concept of post back. The simplest way to detect this client-side would be to have [Insert Your Server Side Language Here] write/set a JavasScript variable on post back.

In C#, it would look a bit like this:

ClientScript.RegisterClientScriptBlock(GetType(), 
         "isPostBack", 
         String.Format("var isPostback = {0};", IsPostBack.ToString().ToLower()),
         true);

JavaScript:

if(isPostback) {
     // Postback specific logic here
}

I use an asp:hiddenfield which gets its value on page_load.

On the client you can get the value as a string using jQuery, compare it to 'true' resulting in a boolean.

HTML:

<asp:HiddenField runat="server" ID="hdnIsPostback" />

VB.NET (in page_load):

Me.hdnIsPostback.Value = Me.IsPostBack

Javascript:

var isPostback = $("#<%=hdnIsPostback.ClientID%>").val().toLowerCase() === "true";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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