How to detect/track postback in javascript?

后端 未结 11 1321
猫巷女王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:28

    In some cases, you may want to check for postback without any server-side code. For example, in SharePoint, you cannot have code blocks in SharePoint Designer pages, so you can't use any solution that requires <%=something %>. Here is an alternative that involves no server-side code:

    <script type="text/javascript">
     function isPostBack()
     {
    
      return document.referrer.indexOf(document.location.href) > -1;
     }
    
     if (isPostBack()){
    document.write('<span style="color:red;">Your search returned no results.</span><br/>');
     }
     </script>
    

    One caveat (or feature, depending on how you look at it), this will detect not just postbacks, but any instance where the page links to itself.

    0 讨论(0)
  • 2020-12-02 19:28

    If you want to check whether the current page will be a postback if the user clicks on a submit button, you can check for the presence of ViewState:

    <input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="xxxxx" />
    

    You can use something like document.getElementById("__VIEWSTATE") or the jQuery equivalent.

    However, if you want to see whether the current page was generated in response to a postback, then you need to insert that data into the page on the server side first.

    For example:

    function isPostBack() {
      return <%= Page.IsPostBack %>;
    }
    
    0 讨论(0)
  • 2020-12-02 19:28

    You can only keep track of the postback if you are using AJAX requests or have a hidden field of some sort that the javascript reads on page load. Otherwise the page is regenerated and all POST data is lost; as you would expect and hope.

    0 讨论(0)
  • 2020-12-02 19:34

    Here is solution using jQuery:

    $("a[href^='javascript:__doPostBack']").click(function () {
        alert('ok');
    });
    
    0 讨论(0)
  • 2020-12-02 19:41

    This is a simple JS way to determine the status of IsPostBack that I just got working in the Body of my ASPX page; needed to cause a PostBack during PageLoad for a project.

        <script type="text/javascript">
            if ('False' === '<%= Page.IsPostBack.ToString()%>') 
            {
                __doPostBack();
            }
        </script>
    
    0 讨论(0)
  • 2020-12-02 19:44

    See following:

    <script type="text/javascript">
    
    function invokeMeMaster() {
    
    var chkPostBack = '<%= Page.IsPostBack ? "true" : "false" %>';
    
    if (chkPostBack == 'false') {
    
    alert('Only the first time');
    
    }
    }
    
    
    
    window.onload = function() { invokeMeMaster(); };
    
    </script>
    
    0 讨论(0)
提交回复
热议问题