我有以下代码,可在需要时提前一个月加载有关用户付款的信息。该功能在我等待每个月加载时有效,但是在运行多个 ajax 请求时它会失败。基本上重复的数据被添加到我的monthData数组中,这意味着loadedPaymentMonth被每个函数调用覆盖。我想异步加载数据,所以有什么想法吗?
这不起作用:
var monthData=[];
function loadMonth(monthToLoad,curMonth){
$("#paymentContent").find(".loader").remove();
var monthToGet;
switch(monthToLoad){
case "Next": monthToGet=monthData.length-curMonth+1;
break;
case "Prev": monthToGet=-curMonth-1;
break;
case "This": monthToGet=currentMonthPointer-curMonth;
break;
}
var loadedPaymentMonth=new PaymentMonth();
if(monthToGet<0){
currentMonthPointer+=1;
monthData.unshift(loadedPaymentMonth);
}
else{
monthData.push(loadedPaymentMonth);
}
$.getJSON(host+"GetDataForMonth.aspx?StartMonth="+monthToGet,function(data){
loadedPaymentMonth.setMonthData(data.monthData,data.month,data.year);
if($("#paymentsContent").find(".loader").remove().length>0){
loadedPaymentMonth.createPaymentRowsForMonth();
}
}).error(function(){
$("#paymentsContent").find(".loader").remove();
});
}
这样做:
function loadMonth(monthToLoad,curMonth){
$("#paymentContent").find(".loader").remove();
var monthToGet;
switch(monthToLoad){
case "Next": monthToGet=monthData.length-curMonth+1;
break;
case "Prev": monthToGet=-curMonth-1;
break;
case "This": monthToGet=currentMonthPointer-curMonth;
break;
}
var loadedPaymentMonth=new PaymentMonth();
if(monthToGet<0){
currentMonthPointer+=1;
monthData.unshift(loadedPaymentMonth);
}
else{
monthData.push(loadedPaymentMonth);
}
$.ajax({
url:host+"GetDataForMonth.aspx?StartMonth="+monthToGet,
async:false,
dataType:"json",
success:function(data){
loadedPaymentMonth.setMonthData(data.monthData,data.month,data.year);
if($("#paymentsContent").find(".loader").remove().length>0){
loadedPaymentMonth.createPaymentRowsForMonth();
}
}
}).error(function(){
$("#paymentsContent").find(".loader").remove();
});
}