开发者

jquery 1.5 Ajax Requests, via Deferred Object, to PageMethod Not Executing as Expected

开发者 https://www.devze.com 2023-02-14 07:32 出处:网络
I have some code where I wish to call a page method for each row in a datatable. Each row contains user information and the page method looks for additional data regarding that user, in a certain time

I have some code where I wish to call a page method for each row in a datatable. Each row contains user information and the page method looks for additional data regarding that user, in a certain time period. If such data exsts, the idea is to then append the data as a new row to the current row. If no such data exists, move on to the next row.

I begin my code with:

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

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

First I retrieve start and end dates via page methods. This works fine. Then I try to call a method for each datarorow in the table:

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

This to works no problem. I pass the current data row to a new function which is:

    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 ca开发者_StackOverflow中文版ll 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.


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?

0

精彩评论

暂无评论...
验证码 换一张
取 消