在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");
});
}
答案 0 :(得分:0)
将其作为ajax请求的选项传递,然后使用this.i访问它。
$.ajax({
...
index: i,
...
success: function(data){
...
alert(this.index);
...
}
})
答案 1 :(得分:0)
一种方法可能是使用闭包。
...
success: (function(i){
return function(data) {
...
olist[i].Pages = str;
...
};
})(i),
...
未测试。
答案 2 :(得分:0)
备受诟病但却很难理解且不受重视的with
:
with ({i:i})
{
/* your ajax code referencing i*/
}