2014-12-05 88 views
0





我剛開始使用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調用)時,模板呈現得很好。

任何人都可以闡明爲什麼會發生這種情況,我該如何解決這個問題?

在此先感謝。

+0

我們不知道你的目錄結構是能夠告訴你爲什麼你會得到404的。記住路徑是相對於發出請求的頁面的url路徑 – charlietfl 2014-12-05 23:36:11

+0

對不起,愚蠢的錯誤我。我會進行編輯,謝謝。 – user1163073 2014-12-05 23:39:25

+0

在沒有解析器「修復」它的html響應中,您是否可以在TR和TBODY標記之間插入垃圾? – dandavis 2014-12-05 23:39:44

回答

1

我設法改變這個來解決該問題:

<script src="http://cdnjs.cloudflare.com/ajax/libs/handlebars.js/2.0.0-alpha.4/handlebars.min.js"></script> 

這樣:

<script src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/2.0.0/handlebars.js"></script> 

感謝所有的建議雖然。

0

這對手把不是問題;這是您的網址問題(如錯誤提示);我注意到您正在使用AJAX請求中的相對路徑

templates/requests.html 

。如果您使用絕對網址(/templates/requests.html),是否解決了問題?

同樣,是不管你使用的後端服務器配置爲服務該目錄?

+0

我試過了,仍然出現同樣的錯誤:'無法加載資源:在此服務器上沒有找到請求的URL:///templates/requests.html?_ = 1417823296897 – user1163073 2014-12-05 23:49:35

+0

你在本地運行嗎?如在中,你是否剛剛在瀏覽器中將你的index.html文件打開了磁盤? 如果是這樣,你會遇到問題,因爲大多數瀏覽器的沙箱AJAX阻止人們訪問用戶的本地文件。 – 2014-12-05 23:57:00

+0

是的,我從桌面上的一個文件夾運行這個。我會嘗試從MAMP運行它? – user1163073 2014-12-06 00:03:21