2

下午,我通过 AJAX 调用检索了一个数组。它带回以下结果,有时包含多个项目

 itemQty: 1
 productBrand: "Brand"
 productPrice: "6.25"
 productShipping: "0.35"
 productSku: "sku"
 productTitle: "ProdTitle"
 OrderId: 123

下面是我的 jQuery 代码,用于对项目进行排序和添加,以生成小计、运输和总计。

 var ordRes = result;

 var subTotal = (ordRes.productPrice * parseInt(ordRes.itemQty)).toFixed(2);
 var orderTotal = (parseFloat(ordRes.productShipping) + parseFloat(subTotal)).toFixed(2);

 $('#ordSubTotal').text("£" + subTotal);
 $('#ordShipping').text("£" + ordRes.productShipping);
 $('#ordTotal').text("£" + orderTotal);

但是,当我带回多个项目时,我无法将它们添加到 subTotal 和 orderTotal 中。有人可以帮我解释一下吗?

* 返回的 JSON *

 {
"d": [
    {
        "__type": "ABO.GetOrdersDetails",
        "tweOrderId": 123,
        "productSku": "sku",
        "productTitle": "ProdTitle",
        "productBrand": "Brand",
        "itemQty": 1,
        "productPrice": "6.25",
        "productShipping": "0.35"
    },
    {
        "__type": "ABO.GetOrdersDetails",
        "tweOrderId": 123,
        "productSku": "sku",
        "productTitle": "ProdTitle",
        "productBrand": "Brand",
        "itemQty": 2,
        "productPrice": "82.58",
        "productShipping": "4.60"
    }
 ]
 }
4

1 回答 1

0
if (result.constructor != Array) {
    result = [result];
}

var subTotal = 0, orderTotal = 0;
for (var i = result.length - 1; i >= 0; i--) {
    var tmp = parseFloat(result[i].productPrice) * result[i].itemQty;
    orderTotal += (parseFloat(result[i].productShipping) + tmp);
    subTotal += tmp;
}

$('#ordSubTotal').text("£" + subTotal.toFixed(2));
$('#ordTotal').text("£" + orderTotal.toFixed(2));

也许它对你有帮助。

于 2012-08-07T16:08:56.690 回答