【问题标题】:ASP.Net ScriptManager -> ServiceReference Ajax calls - Can I catch Start and End Events?ASP.Net ScriptManager -> ServiceReference Ajax 调用 - 我可以捕获开始和结束事件吗?
【发布时间】:2014-01-02 20:37:27
【问题描述】:

我在我的 ASP.Net 4.0 应用程序中本地有一个 WCF 服务。我的 MasterPage 中有以下内容:

<asp:ScriptManager runat="server">
    <Services>
        <asp:ServiceReference Path="~/Services/AJAXDataService.svc" />
    </Services>
</asp:ScriptManager>

然后在我的页面上我有以下 JavaScript 代码:

...
5 calls to the service to fill in drop downs and such
...

$(document).ajaxStop(function () {
    var service = new BOR.AJAXDataService();
    service.GetComplaintDetails(passed, FillComplaint, DefaultFailure, null);
}); // AjaxStop - Event - Everything is done, now load the Model

这发生在大约 5 次其他 ajax 调用之后的 Document Ready 事件中。如果我不将它放在 ajaxStop 事件中,它会起作用,但取决于数据库和网络延迟,它可能不起作用,因为 GetComplaintDetails 需要从之前的每个调用中返回的内容。

我找到了 ajaxStop 方法,并认为它正是我所需要的。但显然 Microsoft/ScriptManager 调用不通过 jQuery(当然),因此该功能毫无意义。

问:在使用 ScriptManager 引用时,有没有办法拦截之前每个调用的being/end、start/stop 事件?我宁愿这样做,也不愿创建冗长冗长的 jQuery 调用。

【问题讨论】:

    标签: javascript asp.net jquery


    【解决方案1】:

    好的,进一步研究它,我想出了一个不错的解决方法。它使用 ASP.Net 客户端框架 (Sys) 使其工作。

    我创建了一个全局变量:

    var _ajaxCounter = 0;
    

    我将以下代码放入我的 global/MasterPage Document Ready 方法中。

    if (Sys.Net.WebRequestManager != undefined) {
        Sys.Net.WebRequestManager.add_invokingRequest(WRMInvoke);
        Sys.Net.WebRequestManager.add_completedRequest(WRMCompleted);
    } // if we have the Sys.Net namespace
    

    然后在每个页面上加载的 .js 文件中,我有两种方法:

    function WRMInvoke(sender, args) { _ajaxCounter++; }
    
    function WRMCompleted(sender, args) {
        _ajaxCounter--;
    
        if ((_ajaxCounter == 0) && (typeof (SomeFinalMethod) != "undefined")) {
            Status_Saving(false);
            Status_Working(false);
    
            SomeFinalMethod();
        }
    }
    

    所以现在在我需要确保在其他所有事情之后发生某些事情的页面上,我只需要定义一个 SomeFinalMethod 方法,如下所示:

    function SomeFinalMethod () {
        var passed = $("#hdnComplaintID").val();
    
        if (passed != "") {
            var service = new BOR.AJAXDataService();
            service.GetComplaintDetails(passed, FillComplaint, DefaultFailure, null);
        }
    
        SomeFinalMethod = undefined;
    }
    

    注意 SomeFinalMethod 的最后一行,它会自行清除。在某些情况下,这是不必要的。但是,在我的页面上,用户可以做的一些事情可能会触发其他 ajax 调用,最后一个会再次调用此方法并创建一个循环。

    作为参考,请查看这篇MSDN 文章。

    希望它可以帮助其他人。

    【讨论】:

      猜你喜欢
      • 2013-02-03
      • 1970-01-01
      • 2023-03-20
      • 1970-01-01
      • 2020-05-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-09-19
      相关资源
      最近更新 更多