2014-12-05 90 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