[英]Take input from html field and store it in JSON object (lots of input fields)
我正在尋找一種從HTML表單獲取輸入並將其存儲到JSON對象以供AJAX使用的方法。 我不能使用普通的$('#id').val();
,因為您可以在下面看到,其中包含許多字段。 這是一些示例代碼
使用Javascript / jQuery的:
$(document).ready(function() {
$('.add-to-cart').click(function() {
var id = $(this).attr('id');
//var qty = $(this).attr('qty'); <- need the quantity from the field
console.log(id);
//console.log(qty);
$.ajax({
url: 'addproduct',
type: 'POST',
datazType: 'JSON',
data: {
"id": id
//"qty": qty
},
success: function(addedproduct) {
console.log(addedproduct.name);
$('#cart').append('<li>'+ addedproduct.name +'</li>');
},
error: function() {
console.log('failed to add product');
}
})
});
});
HTML:
<p class="name">{{$product->name}}</p>
<input type="number" id="qty" class="qty" name="qty">
<button type="submit" id="{{$product->id}}" class="add-to-cart">Add to cart</button>
請幫助我,或者至少在正確的方向上指導我,這必須使用AJAX來實現。
jQuery的selialize方法就是您要尋找的。 它以一種形式序列化輸入的值。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.