就在这里!你也可以重构你的 API。
想象一下,您有一个 API 可以为每个新列表项返回这个 json blob。
{
name: "limelights"
}
让我们为此使用 jQuery(尽管我有点不想这样做。)所以你像这样查询 API
$.getJSON('api/v1/getName.json', {'someParameter', 123}, function() {
//this is where you would do your rendering then.
});
那么如何进行渲染呢?好吧,我是underscore.js的忠实粉丝,它可以渲染模板,所以我会继续使用它(但你可以将它换成 Mustasche、Handlebars、Hogan或任何你喜欢的东西)。
首先,我们将定义一个这样的脚本模板:(我们使用 underscore.js 自己的 ERB 样式模板语言)。
<script type="text/template" id="my_fancy_list">
<li><%= name %></li>
</script>
现在它几乎可以存在于任何地方,无论是在您的模板中,或者如果您使用 Require.JS,您可以在其中使用它,但我们假设它存在于您的模板中(提示:它可以由一些 Django 模板标签呈现)
无论如何,
现在用数据填充这个模板:
var template = _.template($('script#my_fancy_list').html());
//this will give you the template as a javascript function.
//Query the API
$.getJSON('api/v1/getName.json', {'startsWith': 'l'}, function(data) {
$('ul.search-results-list').append(template(data));
});
现在,您现在有了一个 JavaScript 驱动的应用程序,它可以渲染来自服务器的新数据,而无需获取整个模板并再次渲染它。