我有一个从数据库中提取的小部件列表,每个小部件都使用switch语句加载。我遇到的问题是,如果一个getJson
呼叫在另一个呼叫之前完成,即使它进一步下线,它也会无序地装载。我怎样才能防止这种情况发生,以便它们可以按顺序加载?如何在jquery中延迟getJson异步?
var DashboardArray = DashBoardItems.split(",");
for (index = 0; index < DashboardArray.length; index++) {
switch (DashboardArray[index]) {
case 'totalHours':
$.getJSON(hoursByType, function (json) { hrsByTypeJSON = json; HoursByType(); });
break;
case 'invoiceList':
InvoiceListNav();
break;
case 'prevInvoiceWidget':
PreviousInvoice();
break;
case 'payrollSchWidget':
PayrollSchedule();
break;
case 'empListWidget':
EmployeeList();
break;
case 'executiveOverview':
$.getJSON(execOverview, function (json) { execOverJSON = json; ExecOverView(); });
break;
case 'grossWagesDept':
$.getJSON(dashboardURL, function (json) { gwdJSON = json; WagesByDept(); });
break;
case 'grosswagesbyTrend':
$.getJSON(wagesByTrend, function (json) { wageTrendJSON = json; grosswagesbyTrend();});
break;
case 'wagesPos':
$.getJSON(wagesByPosition, function (json) { posJSON = json; WagesByPos(); });
break;
case 'totalreghoursbyTrend':
$.getJSON(RegHrsTrend, function (json1) {
RegHrTrendJSON = json1;
$.getJSON(OTHrsTrend, function (json2) {
OTHrTrendJSON = json2;
$.getJSON(PTOHrsTrend, function (json3) {
PTOHrTrendJSON = json3;
$.getJSON(OtherHrsTrend, function (json4) {
OtherHrTrendJSON = json4;
totalRegHoursTrend();
});
});
});
});
break;
case 'employeeByType':
empTypePie();
break;
case 'totalInvoice':
$.getJSON(totalInvoice, function (json) { TTLInvJSON = json; TotalInvoice(); });
break;
case 'totalInvoiceDept':
$.getJSON(InvoiceByDiv, function (json) { InvDivJSON = json; TotalInvoiceDept(); });
break;
case 'totalinvoicebyTrend':
$.getJSON(InvoiceTrend, function (json) { InvTrendJSON = json; totalInvoiceTrend(); });
break;
}
可能的重复http://stackoverflow.com/questions/18387417/javascript-how-to-implement-a-queue-of-async-functions-without -libraries – phenxd
你需要做的不是延迟你的请求,而是排队。 – phenxd
使用.done(function(){})就像这里解释的那样:[jQuery.getJSON()](http://api.jquery.com/jquery.getjson/)它保存代码在成功的数据检索后执行。 –