2013-11-23 31 views
-1

我想實現類似如下:同步函數調用javascript中

$.getJSON('api/filterTemplate/dashboard', function (data) { 

     $.map(data, function (rec, i) { 
      $.get('commonCore/templates/' + rec.templateHtml, function (html) { 
       filterTemplate = Handlebars.compile(html); 

       replaceFilterTemplate(data[i].classids);// this functions appends html to div -data[i].classids 
      }); 
     }); 
}); 

但由於AJAX異步行爲,HTML不獲取附加到其正確的DIV ID。有人可以幫我用這段代碼,並建議我採取一些方法來做到這一點。

+0

你是什麼意思它不追加到正確的DIV ,附加的數據元素是什麼,這個問題是什麼? – adeneo

+0

你在'map'中有'rec'和'i',你可能應該使用'each' – megawac

+0

'replaceFilterTemplate'依賴'filterTemplate'是全局的嗎?如果是的話,那就是你的問題的一部分。如果不是'filterTemplate'獲得使用的地方? 'replaceFilterTemplate'的代碼代碼 – charlietfl

回答

2

使用一個承諾要維持秩序(見$.when()

$.getJSON('api/filterTemplate/dashboard', function (data) { 
    var promises = []; 
    $.each(data, function (i, rec) { 
     promises.push($.get('commonCore/templates/' + rec.templateHtml)); 
    }); 
    $.when.apply(this, promises).then(function() { //after all requests complete 
     $.each(arguments, function(i, html) { 
      filterTemplate = Handlebars.compile(html); 
      replaceFilterTemplate(data[i].classids);// this functions appends html to div -data[i].classids 
     }) 
    }) 
}); 

此外,我建議你通過filterTempaltesreplaceFilterTemplate而不是它的全球的/納入