有没有办法确保在后续调用执行之前完成第一个AJAX调用?

时间:2011-08-01 13:55:20

标签: jquery asp.net ajax

我正在尝试进行连续的异步ajax调用,以便通过jQuery将用户的日程表绘制到HTML表中。 每个响应都返回一个包含两个表的JSON序列化DataSet:一个是预定事件,另一个是包含用户信息。

我遇到的问题是用户信息似乎与用户事件混淆了。也就是说,有时用户onfo不会 更改不同的响应,以便将计划的事件绑定到不正确的用户。如果我将AJAX async属性设置为false,那么一切都很好。

重点是在返回数据时逐个显示计划,而不是让页面冻结,直到返回所有数据。

有没有办法确保在后续调用执行之前完成第一个JAX调用?

(也许我对将异步设置为false的理解是不正确的。这不是说在代码执行继续之前收集所有数据吗?)

这是我目前的做法:

        //  When page loads
    $(document).ready(function () {
        // Get date range            
        debugger;
    //GetStartDate(), GetEndDate() populates date range
    //PopulateParams() does that for remaining parameters
        $.when(GetStartDate(), GetEndDate())
        .then(function () {
            PopulateParams();
            GetUserSchedule();
        })
        .fail(function () {
            failureAlertMsg();

        })
    });

    // Returns schedule for each person listed in between selected start and end dates
    function GetUserSchedule() {
         for (var i = 0; i < arrRequests.length; i++) {
            $.when(
            // Ajax call to web method, passing in string
            $.ajax({
                type: "POST",
                url: URL/default.aspx/GetSchedules",
                data: arrRequests[i],   // example data: {"UserId":"6115","startDate":"\"7/1/2011\"","endDate":"\"7/31/2011\MoreVals: Vals}                    contentType: "application/json",
                dataType: "json",
                success: SuccessFunction,
                error: function (d) { alert('Failed' + d.responseText + '\nPlease refresh page to try again or contact administrator'); }
            })
            )
            .then(function () {

            }
            );
        }
    }

    // On successful completion of call to web method, paint schedules into HTML table for each user
    function SuccessFunction(data) {            
        if (data != null && data.d != null && data.d.Temp != null) {

        // Calls a bunch of functions to paint schedule onto HTML table
        // Data contains two tables: one contains user info and the other contains rows of info for each event for user
        // at times, the user info is not the correct user or the events are not correct for user
    }

3 个答案:

答案 0 :(得分:1)

$ .ajax中的

({..

写:

 $.ajax({
     async: false,
     **rest of code**});

答案 1 :(得分:0)

也许您可以在之前的成功函数中调用下一个方法,您需要提供一种方法来了解何时停止调用,但您可以向Web服务添加一些信息。所以下一个只在最后一个成功时开始。

答案 2 :(得分:0)

以下是我解决问题的方法。希望它会帮助别人。可能存在一些错别字......这只是为了表明一般的想法。我以递归方式调用了我的GetData方法:

    //  When page loads
    $(document).ready(function () {
        FunctionToBegin();
    });


    // Populates params and call method containing AJAX call
    function FunctionToBegin() {
        // Populate any required params here, including the first param required for the first AJAX call

        // The following block uses the jQuery.Deferred() object, introduced in jQuery 1.5
        // See http://api.jquery.com/category/deferred-object/
        // the object allows us to chain callbacks, **in the order specified**

        // Get date range
        $.when(GetStartDate(), GetEndDate())
            .then(function () {
      var $trCurrent = $('.DataRow:first');
                //Pass in first userID
                GetData($trCurrent.find('td:first').text().trim()); 
            })
                .fail(function () {
                    failureAlertMsg();
                }
           )
    }


    function GetData(userID) {
        // get the user id
        UserId = userID;
        // Create a json string containing data needed to retrieve the required data
        jsonTextStringified = null;
        jsonTextStringified = JSON.stringify({ UserId: UserId, startDate: startDate, endDate: endDate, AdditionalValues: AdditionalValues });
        // Ajax call to web method, passing in string
        $.ajax({
            type: "POST",
            url: "/URL/default.aspx/WebMethod",
            data: jsonTextStringified,
            contentType: "application/json",
            dataType: "json",
            async: true,
            success: SuccessFunction,
            error: function (d) { alert('Failed' + d.responseText + '\nPlease refresh page to try again or contact administrator'); }
        });
    }

    function SuccessFunction(data) {
      if (data != null && data.d != null && data.d.Temp != null) {
    // Do useful stuff


    // Process next user id
            nextUserID = SomeMethod();
            if (nextUserID != 0) { GetData(nextUserID) }
        }
        else {
                 nextUserID = SomeMethod();
                 if (nextUserID != 0) {  GetData(nextUserID) }
            }
        }
    }

此大纲允许在处理下一个呼叫之前完成每个异步调用。换句话说,异步调用组不会立即执行所有操作,因此不会破坏负责返回数据的Web方法。在我的情况下,我返回一个包含两个表的数据集,并且返回的表格不一致准确,除非我将async标志设置为false(不适合我的目的),或者遵循oulined方法。

相关问题