我有几个不同服务的ajax调用。我知道我的数组var log
被每次连续调用覆盖,但我无法弄清楚如何更改逻辑以附加下一个数组而不是覆盖。
$.ajax($.extend({}, ajaxDefaults, source, {
data: data,
success: function(events) {
events = events || [];
var res = applyAll(success, this, arguments);
if ($.isArray(res)) {
events = res;
}
callback(events);
var log = log || [];
for (var i=0; i<events.length; i++) {
log.push(events[i]);
}
console.log(log);
},
error: function() {
applyAll(error, this, arguments);
callback();
},
complete: function(events) {
applyAll(complete, this, arguments);
popLoading();
}
}));
答案 0 :(得分:4)
这只是范围问题。你在$ .ajax success()函数中重新声明'var log'(从而覆盖它)。在$ .ajax之外声明var log,然后将新结果推送到该数组中。
尝试以下方法:
var log = [];
$.ajax($.extend({}, ajaxDefaults, source, {
data: data,
success: function(events) {
events = events || [];
var res = applyAll(success, this, arguments);
if ($.isArray(res)) {
events = res;
}
callback(events);
for (var i=0; i<events.length; i++) {
log.push(events[i]);
}
console.log(log);
},
error: function() {
applyAll(error, this, arguments);
callback();
},
complete: function(events) {
applyAll(complete, this, arguments);
popLoading();
}
}));