0

In the ajax request I need to update olist[i] with the pages returned from the ajax request. How can I make i equal the correct index so I can properly set the pages? I tried adding _index: i to ajax, but could not access it.

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");
});

}

user1167466
  • 333
  • 1
  • 4
  • 14

3 Answers3

0

Pass it as an option to the ajax request then use this.i to access it.

$.ajax({
  ...
  index: i,
  ...
  success: function(data){
    ...
    alert(this.index);
    ...
  }
})
Kevin B
  • 94,570
  • 16
  • 163
  • 180
0

One way may be using a closure.

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

Untested.

Alexander
  • 23,432
  • 11
  • 63
  • 73
0

The much-maligned but poorly understood and unappreciated with:

with ({i:i})
{
    /* your ajax code referencing i*/
}
Plynx
  • 11,341
  • 3
  • 32
  • 33