我剛開始使用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