【问题标题】:Deferred Object's Array and Index Issue延迟对象的数组和索引问题
【发布时间】:2013-01-24 18:59:50
【问题描述】:

在 ajax 请求中,我需要使用从 ajax 请求返回的页面更新 olist[i]。如何使 i 等于正确的索引,以便正确设置页面?我尝试将 _index: i 添加到 ajax,但无法访问它。

function GetPagesList() {
var str, page;
var deferredArr = [], deferr;
startTime = +new Date;

for (var i = 0; i < olist.length; i++) {
    str = [];
    if (olist[i].pagelist == 1) {
        //
    } else {
        deferr =
                $.ajax({
                    type: 'POST',
                    url: 'wfrmHelper.aspx/GetTop10PagesByKey',
                    data: "{Key: '" + olist[i].Key + "'}",
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function(data) {
                        var o = $.parseJSON(data.d);

                        if (o != null) {
                            o.each(function(e, x) {
                                page = e.WebFormName;

                                if ($.inArray(page, Pages2Remove) == -1) {
                                    str.push(page);
                                    totalpages++;
                                }
                            });

                            olist[i].Pages = str; // need to set i
                        }
                    },
                    error: function(xhr, ret, e) {
                        alert('Error');
                    }
                });

        deferredArr.push(deferr);
    }
}

$.when.apply(this, deferredArr).then(function() {
    endTime = +new Date, delta = endTime - startTime;
    log('Total Pages ' + " took:" + delta.toString() + "ms");
});

}

【问题讨论】:

    标签: jquery jquery-deferred


    【解决方案1】:

    将其作为选项传递给 ajax 请求,然后使用 this.i 访问它。

    $.ajax({
      ...
      index: i,
      ...
      success: function(data){
        ...
        alert(this.index);
        ...
      }
    })
    

    【讨论】:

      【解决方案2】:

      一种方法可能是使用闭包。

      ...
      success: (function(i){
          return function(data) {
              ...
              olist[i].Pages = str;
              ...
          };
      })(i),
      ...
      

      未经测试。

      【讨论】:

        【解决方案3】:

        饱受诟病但知之甚少和不受欢迎的with

        with ({i:i})
        {
            /* your ajax code referencing i*/
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2018-11-28
          • 2011-12-17
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多