我刚开始使用handlebars.js尝试从使用字符串连接和注入的丑陋方式渲染动态数据。我试图从主HTML文件中分离模板脚本并通过函数调用来呈现模板文件。
以下是我有:
使用Handlebars.js呈现本地模板
script.js
----------
$(function() {
var myData = { requests: [
{id: "1", firstname: "Roger", lastname: "Jones", age: 24},
{id: "2", firstname: "Phillip", lastname: "Green", age: 44}
]};
$.ajax({
url: 'templates/requests.html',
dataType: 'html',
cache: false,
success: function(data, status, response) {
var template = Handlebars.compile(response.responseText);
var context = myData;
$('#InjectTemplate_Requests').html(template(context));
}
});
});
index.html
-------------
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Handlebars</title>
</head>
<body>
<div id="InjectTemplate_Requests">
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/handlebars.js/2.0.0-alpha.4/handlebars.min.js"></script>
<script src="script.js"></script>
</body>
</html>
requests.html (template file inside the 'templates' directory)
--------------
<table>
<thead>
<th>Name</th>
<th>Status</th>
<th>Type</th>
</thead>
<tbody>
{{#requests}}
<tr>
<td>{{firstname}} {{lastname}}</td>
<td>{{age}}</td>
</tr>
{{/requests}}
</tbody>
</table>
File Structure
--------------
index.html
|
script.js
|
|
|---templates
|
|
|---requests.html
我似乎在控制台上得到这个错误:Failed to load resource: The requested URL was not found on this server.
但是,当我将模板添加到Index.html
(并从脚本文件中删除ajax调用)时,模板呈现得很好。
任何人都可以阐明为什么会发生这种情况,我该如何解决这个问题?
在此先感谢。
我们不知道你的目录结构是能够告诉你为什么你会得到404的。记住路径是相对于发出请求的页面的url路径 – charlietfl 2014-12-05 23:36:11
对不起,愚蠢的错误我。我会进行编辑,谢谢。 – user1163073 2014-12-05 23:39:25
在没有解析器“修复”它的html响应中,您是否可以在TR和TBODY标记之间插入垃圾? – dandavis 2014-12-05 23:39:44