简体   繁体   中英

Javascript After AJAX Request

When the page is loaded, the function commentsShowHideEffect in javascript runs. When ajax request is made all instructions in the method commentsShowHideEffect() are gone. How to recover these isntructions or call commentsShowHideEffect() method again after ajax request ?

<script>
    $(function () {
        commentsShowHideEffect();
    });
</script}

 <asp:UpdatePanel ID="UpdatePanel2" runat="server" UpdateMode="Conditional">
    <Triggers>
        <asp:AsyncPostBackTrigger ControlID="MessageButton" />
    </Triggers>
    <ContentTemplate>
        <asp:Timer ID="RefreshTimer" runat="server" Interval="500" />
            <asp:DataList ID="ChatDataList" runat="server" >
                <ItemTemplate>    
                    <td><asp:Label ID="lblRaterName" runat="server" Text='<%# Eval("Text")%>'></asp:Label></td>
               </ItemTemplate>
            </asp:DataList>
     </ContentTemplate>
</asp:UpdatePanel>

You can bind Sys.WebForms.PageRequestManager endRequest event which will fire after the ajax request is completed by the update panel.

Sys.WebForms.PageRequestManager.getInstance().add_endRequest(EndRequestHandler);
function EndRequestHandler(sender, args)
{
     alert("After ajax call ended");
}

Define the commentsShowHideEffect out of the jQuery scope:

<script>
    function commentsShowHideEffect() {
        //do something
    }

    $(document).ready(function (){
        commentsShowHideEffect();
    });
</script>

Further I prefer to use the document.ready syntax, because it is more clear for the programmer to understand what it is.

You did not mention jQuery in you question and not in the tags either. But you code sees to suggest that you are using it, so here is a link to a relevant doc page :

http://api.jquery.com/ajaxComplete/

In your situation, this should work :

$(document).ajaxComplete(function(event,request, settings) {
   commentsShowHideEffect();
});

Note that the above will trigger for each and every ajax request. If you want more control, you should use the complete or success callback on the individual requests.

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