2016-09-18 140 views
0

我現在已經掌握了這一點代碼,在那裏我得到了頁面所需的所有模板。ajax的承諾

問題是這樣,每次我加載頁面時,ajax請求都沒有以相同的順序完成。

有沒有辦法使用承諾或其他東西,使加載順序始終保持不變?
謝謝。

var loadTemplates = function (templatesObject) { 
    $.each(templatesObject.template, function (index, template) { 
     template.callback = template.callback || $.noop; 

     $.ajax({ 
      url: template.url, 
      success: function(html) { 
       var compiledHtml = Handlebars.compile(html); 
       var output = compiledHtml(template.data); 
       $(template.target).append(output); 
       template.callback(); 
      } 
     }); 
    }); 
}; 

編輯:這是我的對象看起來像怎樣,不同數量的模板,在這個例子中只有2。

templatesObject

var templates = { 
    template: [ 
     { 
      url: 'firsturl', 
      target: '#page-content' 
     }, 
     { 
      url: 'myurl', 
      target: '#page-content', 
      data: data, 
      callback: awesomefunction 
     } 
    ] 
}; 

回答

0

你可以使用一個事實,即$就返回一個承諾,使用$ .MAP而不是$。每次,並使用$。當等待所有的AJAX完成,並做你在$ .when(),然後回調成功回調...

var loadTemplates = function (templatesObject) { 
    $.when.apply($, $.map(templatesObject.template, function (index, template) { 
     template.callback = template.callback || $.noop; 
     return $.ajax({ 
      url: template.url, 
     }).then(function(html) { 
      return {html: html, template: template}; 
     }); 
    })).then(function() { 
     $.each(arguments, function(index, result) { 
      var compiledHtml = Handlebars.compile(result.html); 
      var output = compiledHtml(result.template.data); 
      $(result.template.target).append(output); 
      result.template.callback(); 
     }) 
    }); 
}; 
+0

感謝您的答案,但是當我控制檯登錄模板的時候,我得到0而不是模板對象。 我添加了一個我的對象看起來像是什麼樣子的例子,如果它有任何幫助。謝謝 –

+0

每個參數都是一個數組,數據是該數組的第一個元素。另外'arguments'就是數組像對象 – charlietfl

+0

d'oh,是的 - 我沒有完全讀取代碼 –