嗨我有這個問題,當我想用html中的按鈕刪除我的json條目。現在我有一個/data.json
,/views/home.handlebars
,/public/js/home.js
,public/routes/home.js
,etc
的結構。我試圖定義一個<script>
標籤的功能,但由於控制檯說:"data is not defined"
用html按鈕更改json
這裏是data.json
{
"receipts": [
{
"receipt_ID": "1",
"purchase_month": "2",
"purchase_day": "12",
"purchase_year": "2017",
"seller": "Trader Joe's",
"#_of_items": "3",
"items_array": [ "1001", "1002", "1003" ],
"imageURL": "",
"uploader_ID": "Dominic",
"note": "Dominic bought this at TJ",
"deleted": "0"
},
{
"receipt_ID": "2",
"purchase_month": "2",
"purchase_day": "10",
"purchase_year": "2017",
"seller": "Von's",
"#_of_items": "2",
"items_array": [ "2001", "2002" ],
"imageURL": "",
"uploader_ID": "Dominic",
"note": "Dominic bought this at Vons",
"deleted": "0"
}
],
"item": [
{
"receipt_ID": "1",
"item_index": "1",
"item_ID": "1001",
"item_catalog": "fruit",
"item_name": "Apple",
"item_imageURL": "/image/item_icon/apple.png",
"expiration_month": "2",
"expiration_day": "28",
"expiration_year": "2017",
"price_per_unit": "1.99",
"unit": "lbs",
"amount": "3.2",
"total_price": "6.37",
"shareable": true,
"wasted": "0",
"used_up": "0"
},
{
"receipt_ID": "1",
"item_index": "2",
"item_ID": "1002",
"item_catalog": "drink",
"item_name": "Diet Coke",
"item_imageURL": "/image/item_icon/drinks.png",
"expiration_month": "8",
"expiration_day": "31",
"expiration_year": "2017",
"price_per_unit": "0.99",
"unit": "count",
"amount": "5",
"total_price": "4.95",
"shareable": true,
"wasted": "0",
"used_up": "0"
}]
}
下面是HTML函數調用,用<script>
標籤
<ul class="private_shelf">
{{#each item}}
<li herf="/item/{{item_ID}}" class="food">
{{item_name}}
<img src="{{item_imageURL}}" class="food_icon">
</li>
<button onclick="removeItem({{item_index}})">Remove Item</button> {{/each}}
</ul>
<script>
function removeItem(cid) {
console.log("removing");
data.item.splice(cid, 1);
}
$.getJSON('data.json', function(data) {
//do stuff with your data here
});
</script>
當我把劇本部分public/js/home.js
,函數調用正確(控制檯顯示"removing"
),但它說的數據沒有在這裏定義,要麼是需要()定義。
但是,當我把功能放在routes/home.js
,函數根本不被調用。
如何從HTML中的按鈕中刪除data.json
中的條目以及javascript函數應該在哪個文件中?
在此先感謝。
更新: Here is my folder hierarchy
我做$.getJSON('/data.json', function(data){ data = data; });
現在,但控制檯仍響應「GET本地主機:3000/data.json 404 NOT FOUND在不removeItem
訪問
您需要爲此使用nodejs – pudility
您的數據對象在哪裏?一個全球變量? –
我的數據對象立即在根文件夾中。因此,如果html位於/views/home.handlebars,json位於/data.json –