【发布时间】:2012-01-26 16:52:06
【问题描述】:
我正在制作一个小型购物车。目前我正在尝试实现结帐功能,该功能在进入付款页面之前检查每个产品的库存。
此 while 循环显示“购物车”表中的每一行:
while ($row = $result->fetch()) {
echo '<table class="cart-row" cellspacing="0" cellpadding="0" width="100%">';
echo '<tbody>';
echo '<tr>';
echo '<td width="75"><img border="0" width="59px" height="78px" title="" alt="" src=' . $row["ImagePath"] .'></td>';
echo '<td width="203"><span class="itemElements itemName">'. $row["Name"] .'</span></td>';
echo '<td width="203"><input type="submit" class="btnMinus linkbtnType2" value="-"><input type="submit" class="btnPlus linkbtnType2" value="+"></td>';
echo '<td width="135"><span class="qtyNum">('. $row["Qty"] .')</span> <br />';
echo '<input type="hidden" name="ProductId" class="ProductId" value='.$row["ProductId"].' />';
echo '<span class="qtyRemoveLink"><input type="submit" class="btnRemove linkbtn" value="Remove"></td>';
echo '<td width="180"><span class="itemElements orderStatus">In Stock Usually dispatched within 24 hours</span></td>';
echo '<td width="175" class="itemPriceRow"><span id="itemPrice">€ '. $row["Price"]* $row["Qty"] .'</span></td>';
echo '</tr>';
echo '</tbody>';
echo '</table>';
echo '<br>';
}
在那个 while 循环中,一个隐藏的输入按钮的值正在加载,其中 productId 对应于返回的行。
现在我有了这个 jQuery 方法,它应该读取页面中的所有 procuctId 值并将它们存储在一个数组中。
$('#btnCheckout').click(function () {
var productId = new Array();
var j = 0;
$(".ProductId").each(function () {
productId[j] == $(this).val();
j++;
});
$.ajax({
type: "POST",
url: "functions/checkProductStock.php",
data: {
productId: JSON.stringify(productId)
},
success: function (msg) {
alert(msg);
}
})
})
然后,此方法将这些值传递给 PHP 方法:
<?php include "../config.php" ?>
<?php
$productIds = json_decode($_POST['productId']);
var_dump($productIds);
//foreach loop that iterate through an array containing the product IDs and exexcutes the below method.
foreach ($productIds as $productId)
{
$CartDAL = new CartDAL();
$result = $CartDAL->get_ProductInCartById($productId, $_SESSION["username"]);
$result = $ProductsDAL->get_ProductById($productId);
$rowProduct = $result->fetch();
//Get Product Quatity Form Cart
$qty = $row["Qty"];
//Get Product Stock
$stock = $rowProduct["AvailableStock"];
if($qty <= $stock)
{
$CartDAL->remove_ProductInCart($productId, $_SESSION["username"]);
}
else
{
echo $rowProduct["Name"].' is out of stock!';
}
}
?>
不知何故,当我使用 firebug 时,传递给此方法的唯一值是 productId=%5B%5D。仅供参考,应该传递的值是 1 和 2。任何想法为什么错误的值被读取并在数组中传递?还是我上面的方法搞错了?
【问题讨论】:
-
你能显示生成的 HTML 而不是生成它的 PHP 吗?
-
这是什么意思,如果 qty ,此按钮不会生成任何 html 只是一条错误消息
-
生成 HTML 表格的 PHP。 HTML 会更有用。