如何在JQuery中获取所有元素并将它们作为数组发送

3

每当用户选择商品时,我的购物车代码会根据选择生成以下结构。每个tr代表一个商品,x表示基于该商品的不同值,id是该商品的ID。因此,每次的xid和数量都不同。

<tr>
    <td><span class="product-id" value="x"></span></td>
    <td><img class="product-img" value="x" /></td>
    <td><a class="product-name" value="x"></a></td>
    <td><span class=product-color value="x"></span>
    <td><select  class="qnty-id" value="x"></select></td>
    <td><span class="price-id" value="x"></span></td>
    <td><span class="total-id" value="x"></span></td>
</tr>

我想将它们以数组或Json格式收集起来,就像这样:
array(x => array(
    'id'=>'product-id',
    'name'=>'product-name',
    'color'=>'product-color',
    'quntity'=>'qnty-x',
    'price'=>'price-x',
    'total'=>'total-x')
)

使用Ajax将它们发送到我的服务器端。 我会非常感激任何帮助。


@Rajaprabhu Aravindasamy 你能帮助我吗? - Mahdi Younesi
1个回答

1
考虑您的表格 ID 为 table,请尝试以下代码:

var table = $('#table');
var elems = table.find('tr');
var cartArray = [];
elems.each(function (i, item) {
    var itemSelector = $(item);
    var id = itemSelector.find('.product-id').attr('value');
    var img = itemSelector.find('.product-img').attr('value');
    var name = itemSelector.find('.product-name').attr('value');
    var color = itemSelector.find('.product-color').attr('value');
    var quantity = itemSelector.find('.qnty-id').val();
    var price = itemSelector.find('.price-id').text();
    var total = itemSelector.find('.total-id').text();
    cartArray.push({id: id, img: img, name: name, color: color, quantity: quantity, price: price, total: total});
});
console.log(cartArray);

你需要在不同的情况下对其进行测试,它必须能够遍历表格中的所有行并正常运行。 - Rayon
谢谢,稍作更改就奏效了。但是现在当我使用Ajax传递数组时,在服务器端得不到适当的结果。 - Mahdi Younesi
@Mahdi Younesi,我无法理解问题。您需要将JSON发送到服务器而不是JavaScript数组... - Rayon

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接