我正在向/cart.js
發出GET請求。它返回以下JSON數據:如何通過Shopify商店中的handlebars.js循環使用JSON數組?
{
"token":"118aa66ff7cc99c7fb4524f07bd305a4",
"note":null,
"attributes":{
},
"total_price":771,
"total_weight":0,
"item_count":3,
"items":[
{
"id":903858951,
"title":"Aarts Frambozen op siroop",
"price":211,
"line_price":211,
"quantity":1,
"sku":"wi195688",
"grams":0,
"vendor":"Aarts",
"properties":null,
"product_id":385866167,
"variant_id":903858951,
"gift_card":false,
"url":"/products/aarts-frambozen-op-siroop?variant=903858951",
"image":"https://cdn.shopify.com/s/files/1/0656/8697/products/AHI_434d50303234343731_dRevLabel_1_Rendition_LowRes_JPG.jpeg?v=1413443204",
"handle":"aarts-frambozen-op-siroop",
"requires_shipping":true
},
{
"id":903852739,
"title":"AH Aardappelschijfjes spek en ui",
"price":211,
"line_price":211,
"quantity":1,
"sku":"wi202676",
"grams":0,
"vendor":"AH",
"properties":null,
"product_id":385862935,
"variant_id":903852739,
"gift_card":false,
"url":"/products/ah-aardappelschijfjes-spek-en-ui?variant=903852739",
"image":"https://cdn.shopify.com/s/files/1/0656/8697/products/AHI_434d50303038363632_dRevLabel_2_Rendition_LowRes_JPG.jpeg?v=1413442904",
"handle":"ah-aardappelschijfjes-spek-en-ui",
"requires_shipping":true
},
{
"id":903852571,
"title":"AH Aardappelen iets kruimig voordeelzak",
"price":349,
"line_price":349,
"quantity":1,
"sku":"wi127728",
"grams":0,
"vendor":"AH",
"properties":null,
"product_id":385862819,
"variant_id":903852571,
"gift_card":false,
"url":"/products/ah-aardappelen-iets-kruimig-voordeelzak?variant=903852571",
"image":"https://cdn.shopify.com/s/files/1/0656/8697/products/AHI_434d50303233343335_dRevLabel_1_Rendition_LowRes_JPG.jpeg?v=1413442897",
"handle":"ah-aardappelen-iets-kruimig-voordeelzak",
"requires_shipping":true
}
],
"requires_shipping":true
}
我希望做的是迭代器在items
並顯示id
,title
和quantity
。
這裏就是我想:
<script class="foobar" charset="utf-8" type="text/x-handlebars-template">
<div>
{{#items}}
<thead>
<th>Id</th>
<th>Title</th>
<th>Qty</th>
</thead>
<tbody>
<tr>
<td>{{id}}</td>
<td>{{title}}</td>
<td>{{quantity}}</td>
</tr>
</tbody>
{{/items}}
</div>
</script>
<script charset="utf-8">
var source = $(".foobar").html();
var template = Handlebars.compile(source);
var jqxhr = $.getJSON("/cart.js", function() {
console.log("success");
})
$('body').append(template(jqxhr.responseJSON));
</script>
但這返回:
Id Title Qty
沒有任何數據。我知道GET請求正在工作,因爲console.log(jqxhr.responseJSON);
會打印正確的數據。
我做錯了什麼,接下來我可以嘗試什麼?
編輯:
我想我錯處理Ajax響應。
的jsfiddle:http://jsfiddle.net/narzero/4fn3f6sg
編輯2:
這可能是值得一提的是我運行一個Shopify商店代碼。
使用'{{#each項目}} {{id}} {{/每個}} – 2014-10-16 13:29:14
http://jsfiddle.net/h2qyh8f2/這是您想要做的事情嗎? – 2014-10-16 13:34:32
@DennisMartinez這正是我想要的。但是當我用真正的JSON數據使用它時,它不起作用。我想我錯誤地處理了json響應。看看這個JSFiddle:http://jsfiddle.net/narzero/kgtLpe5g/ – narzero 2014-10-16 13:39:39