[英]How build an array with html ids, and then send it as JSON with ajax in Javascript Button onClick?
[英]javascript - How to assign json data to an HTML element and send to API onclick?
我正在嘗試創建一個JavaScript框架,在該框架中,我可以使用戶能夠在其帳戶中的電子商務網站中存儲商品,說明,價格等,以供將來參考。 我嘗試執行此操作的方法是在每個顯示“保存項目”的項目旁邊創建一個按鈕,以JSON的形式獲取項目詳細信息,並將其發送到API,以便用戶以后可以訪問它。
到目前為止,我仍然遇到一些基本的設計問題:
假設JSON只有四個字段-1)ItemName 2)物料價格3)物料描述4)零售商物料URL
1)如何存儲四個字段並將它們分配給HTML按鈕-我采用的方法是創建一個類來檢測按鈕的類型,但是我將頁面中所有項目的詳細信息存儲在數組並獲取被單擊的按鈕項的詳細信息,將其放入json並使用jQuery發出發布請求
2)一些研究表明,KnockoutJS可以提供幫助。 顯然,我可以將json存儲為該項目的HTML按鈕的屬性。 這樣安全嗎?
3)如何將API密鑰(每個電子商務零售商都唯一)以及JSON傳遞給API?
我是JavaScript新手,任何幫助將不勝感激!
項目HTML
<table border="1" cellpadding="5">
<tr>
<td> Product 1 </td>
<td>
<button type="button" class="SaveItemButton"
data-item-name="Product 1" data-item-price="1" data-item-description="Description 1" data-retailer-item-url="URL 1">
Save Item
</button>
</td>
</tr>
<tr>
<td> Product 2 </td>
<td>
<button type="button" class="SaveItemButton"
data-item-name="Product 2" data-item-price="2" data-item-description="Description 2" data-retailer-item-url="URL 2" />
Save Item
</button>
</td>
</tr>
</table>
並包括JavaScript
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" type="text/javascript"></script>
<script>
(function($){
window.SomeApiKey = '';
// This is the JS file contents which will be saved as file somewhere and included like the jQuery library above
$(document).ready(function(){
$('.SaveItemButton').click(function(){
var btn = $(this);
// colect data
var data = {'item-name': btn.data('item-name'),
'item-price': btn.data('item-price'),
'item-description': btn.data('item-description'),
'retailer-item-url': btn.data('retailer-item-url'),
'api-key': window.SomeApiKey};
// this line just for testing
alert(' will send :' + $.param( data ) );
// do JSONP request
$.ajax({
type: "GET",
url: "http://www.site.com",
dataType: "jsonp",
data: data
}).done(function( msg ) {
alert( msg );
});
return false;
});
});
})(jQuery);
</script>
<script>
// here the client will set APIkey to use
window.SomeApiKey = 'APIKEY';
</script>
如果要附加數據,請使用HTML5的data屬性,並像這樣從JQUery獲取數據:
<button id="myButtonId" data-ItemName="your value" data-ItemPrice="10.00" data-ItemDescription="Your description" >Your button</button>
然后,使用JQuery可以檢索數據或設置數據,有關主題,請參見JQuery手冊:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.