2013-10-19 43 views
0

我試圖用underscore.template通過加載一個html通過jQuery.get這樣編譯一個JavaScript模板的HTML文件:負荷_.template

_.template($.get('my_template.html'), $get(function(data) { 
    return data; 
})); 

,但我得到了以下信息

TypeError: Object #<Object> has no method 'replace' 

任何提示?

回答

3

$.get不按照您認爲的方式工作。 $.get('my_template.html')不返回my_template.html,它返回一個​​,你得到的東西傳遞給$.get回調:

$.get('my_template.html', function(html) { 
    // my_template.html will be in `html` here. 
}); 

所以,如果你真的想用$.get檢索您的模板,你會必須等待AJAX​​調用才能從服務器返回某些內容,並且直到稍後纔會發生。

異步(默認:true
類型:您可以使用async選項$.ajax做同步AJAX請求布爾
默認情況下,所有的請求都是異步發送(即此設置爲true默認)。如果您需要同步請求,請將此選項設置爲false。 [...]請注意,同步請求可能會暫時鎖定瀏覽器,並在請求處於活動狀態時禁用任何操作。

這將是這樣的:

var tmpl; 
$.ajax({ 
    url: 'my_template.html', 
    type: 'get', 
    async: false, 
    success: function(html) { 
     tmpl = html; 
    } 
}); 
var t = _.template(tmpl); 
// `t` is now your compiled template function 

我不推薦,雖然這,async:false是做給用戶一個討厭的東西,並用它會讓人覺得你的應用程序已鎖定或墜毀。

我會找到一種不同的方式來加載你的模板。將它們全部扔在<script>元素中,以便它們始終可用或隨JavaScript一起使用它們。