當鬍子JS模板(或一般JS模板)的工作,你不需要有模板是在相同的位置從Ajax調用返回的數據。但是,您需要將數據存儲在模板的渲染函數範圍內的var中。我假設你希望在一組數據中使用ajax,將其解析爲JSON,然後在某個時刻將該JSON數據呈現給DOM。因此,要回答你的問題:
1)是否模板必須包含在JSON數據是頁? 不一定,但您需要能夠從一個位置訪問這兩個部分(例如,您可以在模板和數據中都使用ajax,然後將它們放在一起;或者,您可以將模板作爲腳本存儲在DOM中[建議的方式,除非你使用的是AMD],然後當你的ajax調用完成時渲染模板)。
主要要注意的是,你需要有你的模板,並在同一範圍內的數據既是一個參考。
2)設置模板/數據?
這可以通過使用Ajax的成功回調來完成:https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest
那麼成功,你可以有函數調用呈現在你的模板,或者只是設置一個本地變量與數據和處理模板渲染後。
3)使該模板通常
var template = $('#template').html(), //script tage with id="template" from your dom
data = jsonData, //saved somewhere in a local scoped var .. maybe from an ajax call
rendered = Mustache.render(template, data),
target = $("#target"); //where the template renders to
$('#target').html(rendered);
4)呈現通過$就
$.ajax("/api/data", function(data){
var jsonData = $.parseJSON(data),
template = $('#template').html(), //script tage with id="template" from your dom
rendered = Mustache.render(template, jsonData),
target = $("#target"); //where the template renders to
});
數據在一個變種的模板相同的被它的硬編碼或通過AJAX虹吸在。 – dandavis