第一次接触handlebars ,结合别人的json写个例子


<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1, user-scalable=no">
<title>handlebars-食谱测试</title>
<script src="js/jquery-1.9.1.min.js"></script>
<script type="text/javascript" src="../js/handlebars.js"></script>
</head>
<body>
<div id="rest">
</div>

<script id="Handlebars-Template" type="text/x-handlebars-template">
 <div id="Content">
  <h1>ΞRecipeCards
    <span id='BOS'>Recipe search powered by
      <a id='Logo' href='http://www.yummly.com/recipes'>
        <img src='http://static.yummly.com/api-logo.png'/>
      </a>
    </span>
  </h1>
  {{#each Recipes}}
  <div class='Box'>
    <img class='Thumb' src="{{{smallImageUrls}}}" alt="{{recipeName}}">
    <h3>{{recipeName}} <a id='Logo' href="{{Source.Url}}"> - {{{smallImageUrls}}}</a></h3>
    <h5>{{getFlavor Flavors}}</h5>
    <h5>{{sourceDisplayName}}</h5>
    <p>Ingredients:</p>
    <ul>
      {{#each ingredients}}
      <li>{{this}}</li>
      {{/each}}
    </ul>
  </div>
    {{/each}}
</div>
</script>


<script type="text/javascript">

$(function(){
var result = null;
$.ajax({
async: false,
url: "http://api.yummly.com/v1/api/recipes?_app_id=fd47c664&_app_key=99aa6ecb68f1243a79614c84b1834814&images=large",
//url:"http://localhost:8080/mininet/static/didi/wap/test.json",
//dataType: 'json'


dataType:"jsonp",
jsonpCallback:"callback",


})
//如果用平时的ajax方式,会有跨域问题,解决用jsonp
/**.done(function ( rtn ) {

if (typeof (rtn) === 'object') {
result = rtn;
} else {
result = jQuery.parseJSON(rtn)
}
var source = $("#Content").html();
var Source = $("#Handlebars-Template").html();
  //Compile the actual Template file
  var Template = Handlebars.compile(Source); //Generate some HTML code from the compiled Template
  var HTML = Template({ Recipes : result.matches });

$("#rest").html(HTML)

});**/



});
//json请求回调函数(jsonp 解决跨域问题)
function callback(rtn) {
if (typeof (rtn) === 'object') {
result = rtn;
} else {
result = jQuery.parseJSON(rtn)
}
var Source = $("#Handlebars-Template").html();
   var Template = Handlebars.compile(Source); //Generate some HTML code from the compiled Template
   var HTML = Template({ Recipes : result.matches });

$("#rest").html(HTML)
}
//自定义helpers
Handlebars
.registerHelper("getFlavor",
function(FlavorsArr){
var H = 0;
var Name = '';
for(var F in FlavorsArr)
{
if(FlavorsArr[F] > H)
{
H = FlavorsArr[F];
Name = F;
}
}
return "This Dish has a " + Name + " Flavor";
});
</script>
</body>
</html>


期间遇到跨域问题,使用jsonp解决。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值