0

我有一些代码,我希望为数据表中的每一行调用一个页面方法。每行包含用户信息,页面方法在特定时间段内查找有关该用户的其他数据。如果存在此类数据,则想法是将数据作为新行附加到当前行。如果不存在此类数据,请转到下一行。

我开始我的代码:

        $.when(GetStartDate(), GetEndDate())
            .then(function () {                    
                GetSchedules();

            })
            .fail(function () {
                failureAlertMsg();
            })

首先,我通过页面方法检索开始日期和结束日期。这工作正常。然后我尝试为表中的每个数据行调用一个方法:

    function GetSchedules() {
        $('.DataRow').each(function () {
           GetUserSchedule($(this));
        });
    }

这工作没问题。我将当前数据行传递给一个新函数,即:

    var currDataRow;
    var currUserID;

    function GetUserSchedule(dr) {
        currDataRow = dr;
        currUserID = currDataRow.find('td').eq(0).text().trim();
        $.ajax({
            type: "POST",
            url: "mypagewithjqueryurl.aspx/GenerateUserSchedule",
            data: "{'StartDate':'" + startDate + "', 'EndDate':'" + endDate + "', 'UserID':'" + currUserID +"'}",    //params
            contentType: "application/json",
            dataType: "json",
            success: function () {
                alert('Succeeded');
            },
            error: AjaxFailed
        });
    }

When I step through the code, the function is called for each row, currDataRow and currUserID is populated as expected, and the ajax call is performed and here is where the problem lies. The call is made but neither success nor error functions are called until the calls are completed for all rows. Then the success method is called for each row but the required data has been lost.

How can I restructure my code so that the success function is called for each ajax request?

Thanks in advance for any insight.

4

1 回答 1

1

Ajax calls from jquery are asynchronous by default, so it is likely that a handful of calls would all be initiated before any of them succeeds or fails. If you want them to be synchronous, you need to add async: false as a parameter.

You are also limited to two async requests simultaneously, which is also I'm sure a factor here.

This doesn't seem like the best architecture- why not combine all the data into a single request, and set your WebService/PageMethod up so it can handle an array or collection? This is a simpler architecture and will also perform much better than one request per row.

To pass an array, in C# you'd do something like this in your method:

using System.Runtime.Serialization;
...

        [Serializable]
        class Data {
           DateTime StartDate; 
           DateTime EndDate;
        }

    // or really any serializable IEnumerable
        public static MyMethod(string data) {
            JavaScriptSerializer serializer = new JavaScriptSerializer();
            Data[] data = (Data[])serializer.Deserialize(data); 
            foreach (Data item in data) {
              // do stuff
            }
        }

in Javascript, make your array (or object), e.g.

    var dates = Array();
    // loop
    var datestruct = {
      StartDate: startDate,
      EndDate: endDate 
    }
    dates[index]=dateStruct;
    // end loop

then for data: in your $.ajax:

$.toJSON(dates)

You could also build the string manually the way you are now, brackets [] delineate array elements. e.g.

"{['StartDate':'"+startDate+"','EndDate':'"+endDate+"'],['StartDate ... ]}"

but why not use something like JSON serializer that does it for you?

于 2011-03-01T17:30:35.583 回答