有沒有更有效的方法來編寫以下內容?我需要通過objList循環並將UnqKey傳遞給wfrmPrint。在成功之後,我必須循環頁面。我通過傳遞一個整數並檢查它是否小於長度來遍歷頁面和unqkeys。我嘗試使用.when.apply取自http://www.tentonaxe.com/index.cfm/2011/9/22/Using-jQuerywhen-with-a-dynamic-number-of-objects,但它是加載unqkeys然後加載頁面。Ajax請求循環並等待直至完成
//sample objList
[
{
"UnqKey": 1,
"Pages": [
"wfrmSet1Page1.aspx",
"wfrmSet1Page2.aspx"
]
},
{
"UnqKey": 2,
"Pages": [
"wfrmSet2Page1.aspx",
"wfrmSet2Page2.aspx",
"wfrmSet3Page2.aspx",
"wfrmSet4Page2.aspx"
]
}
]
function Loop(iListIndex) {
var obj = objList[iListIndex];
if (iListIndex < objList.length) {
jQuery.ajax({
type: "GET",
url: 'wfrmPRINT.aspx?action=LoadSession&UnqKey=' + obj.UnqKey, //load session that is used in wfrmSet1Pages.. or wfrmSet2Pages..
success: function() {
AddPages(obj, iListIndex, 0);
}
})
} else {
alert('Done');
}
}
function AddPages(obj, iListIndex, iPageIndex) {
if (iPageIndex < obj.Pages.length) {
jQuery.ajax({
type: "GET",
url: obj.Pages[iPageIndex] + '?Print=1', //load html
async: true,
success: function (html) {
iPageIndex++
AddPages(obj, iListIndex, iPageIndex);
},
error: function() {
alert('Failed!');
iPageIndex++
AddPages(obj, iListIndex, iPageIndex);
}
});
} else {
iListIndex++
Loop(iListIndex);
}
}
你知道嗎,你只需要編寫'jQuery'在其漫長的形式一次?通過將代碼封裝在'(function($){....})(jQuery);'中,無論是否使用了noConflict,都可以使用'$'。 – ThiefMaster
如果你想交替發送到wfrmPRINT,然後來回打印,而不是發送所有的一個,那麼所有的另一個,$ .when可能不會是一個選項,你的循環或類似的循環將是替代。但是,如果它可以接受發送所有wfrmPRINT,那麼當它們全部完成循環併發送所有?Print時,可以使用$ .when完成。 –
使用'$ .when'時什麼都不起作用?而且:你是否需要依次或並行地觸發ajax請求? – Bergi