How to detect/track postback in javascript?

后端 未结 11 1384
猫巷女王i
猫巷女王i 2020-12-02 18:51

How to detect/track/check postback in javascript(e.g in asp.net Page.isPostBack())? Any suggestion?

11条回答
  •  死守一世寂寞
    2020-12-02 19:47

    As JavaScript shouldn't be written with server-side code, and injecting new elements into the page seems like overkill, it seems to me that the simplest solution is to add [datat-*] attributes to the element:

    In Page_Load:
    Page.Header.Attributes["data-is-postback"] IsPostBack ? "true" : "false";
    

    This can then be accessed as:

    jQuery:
    $('head').data('isPostback');
    
    Vanilla JS:
    document.head.getAttribute('data-is-postback') === 'true';
    

    Of course, if you treat the [data-is-postback] attribute as a boolean attribute, you could alternatively use:

    In Page_Load:
    if (IsPostBack)
    {
        Page.Header.Attributes.Add("data-is-postback", "");
    }
    else
    {
        Page.Header.Attributes.Remove("data-is-postback");
    }
    
    jQuery:
    $('head').is('[data-is-postback]');
    
    Vanilla JS:
    document.head.hasAttribute('data-is-postback')
    

提交回复
热议问题