weixin_33720452 2017-07-20 15:37 采纳率: 0%
浏览 72

如何实现循环 ajax 调用?

我需要在上一个操作完成后循环进行一次ajax调用:

for (var year = 2000; year <= 2017; year++) 
{ 
    $.ajax(
    {
        url: 'calendar.php?year=' + year,
        beforeSend: function()
        {
            console.log('Loading year: ' + year);
        },
        success: function(result)
        {
            $('#events').append(result);
        }
    });
}

但是当我检查控制台时发现,所有调用都是同时进行的。

  • 写回答

2条回答 默认 最新

  • 叼花硬汉 2017-07-20 15:51
    关注

    You could use the Promise API of jQuery to chain up the requests. Whenever on request is finished the queryYears is called another time with the year incremented by one, until year is larger then maxYear

    function queryYears(year, maxYear) {
      // check if the year is less or equal maxYear
      if (year <= maxYear) {
        return $.ajax({
            url: 'calendar.php?year=' + year,
            beforeSend: function() {
              console.log('Loading year: ' + year);
            }
          })
          .then(function(result) {
            $('#events').append(result);
    
            //incremenat year by one
            year++;
    
            //only call queryYears if year is less or equal to maxYear
            if (year <= maxYear) {
              return queryYears(year, maxYear);
            }
          })
      } else {
        // if not return a rejected Promise
        return Promise.reject(new Error(year + ' is larger then ' + mxYear))
      }
    }
    
    
    
    queryYears(2000, 2017)
    .then(function() {
      console.log('finished')
    })
    .catch(function(err) {
       console.log('failed with: ')
       console.dir(err)
    });
    
    评论

报告相同问题?