我有一個從數據庫中提取的小部件列表,每個小部件都使用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/)它保存代碼在成功的數據檢索後執行。 –