2013-11-23 34 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而不是它的全球的/纳入