【问题标题】:Is there a way to ensure that the first AJAX call completes before the subsequent call executes?有没有办法确保第一个 AJAX 调用在后续调用执行之前完成?
【发布时间】:2011-08-01 13:55:19
【问题描述】:

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

我遇到的问题是用户信息似乎与用户事件混淆了。也就是说,有时用户 onfo 不会 更改不同的响应,以便计划的事件与不正确的用户相关联。如果我将 AJAX 异步属性设置为 false,则一切正常。

重点是在返回数据时一一显示时间表,而不是在返回所有数据之前冻结页面。

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

(也许我对将 async 设置为 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
    }

【问题讨论】:

    标签: jquery asp.net ajax


    【解决方案1】:

    在 $.ajax({..

    写:

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

    【讨论】:

    • 我对将 async 设置为 false 的理解是否不正确?不是说在代码继续执行之前所有数据都被收集了吗?)
    • @Bengal - 我相信你的理解是正确的。但是,如果您的第二次 ajax 调用在您的第一次之后,并且您的第一次被标记为“async:false”,那么第一次调用确实会在第二次调用启动之前完成。
    • 完全正确 :) 只需在第一个 ajax 请求上将 async 设置为 false。
    • 对,我没有提到我已经按照你的建议做了,但是这违背了最初的目的......检索第一个用户的日程安排,在检索后续用户的日程安排时开始将其绘制到页面上时间表等等。我曾希望有人可以提供一个进行后续异步调用而不是并发调用的示例。我怀疑它可能通过递归来实现
    • 正如其他人所提到的,我最好的选择也是使用成功回调来检索下一个请求。不知何故有一个请求列表(也许是 switch-case 函数),然后每次你请求某些东西时,迭代一个计数器以发出下一个请求。
    【解决方案2】:

    也许您可以在上一个的成功函数中调用下一个方法,您需要提供一种知道何时停止调用的方法,但您可以在您的网络服务中添加一些信息。所以下一个只有在最后一个成功时才开始。

    【讨论】:

      【解决方案3】:

      这是我解决问题的方法。希望它会帮助别人。可能有一些错别字......这只是为了展示一般想法。我递归地调用了我的 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 方法。

      【讨论】:

      • 我没有得到这个建议的荣耀,但你的回答更有帮助。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-05-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多