通过json传递jquery数组给PHP


pass jquery array to php with json

我正在构建一个小型购物车。目前,我正在尝试实现结账功能,该功能在进入付款页面之前检查每个产品的库存。

这个while循环显示"shoppingcart"表中的每一行:

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方法,它应该读取页面中的所有productid值并将它们存储在一个数组中。

$('#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。任何想法为什么错误的值被读取和传递到数组?或者我在上面的方法中犯了一个错误?

这是不正确的:

productId[j]==$(this).val();

你在做一个相等性检查==而不是赋值=

更改为:

productId[j]=$(this).val();

你可以这么做

  data: { productId : productId },
that's it! now you can access it in PHP:
   <? $myArray = $_REQUEST['productId ']; ?>

var myJSONText = JSON.stringify(myObject);

['Location Zero', 'Location One', 'Location Two'];

将成为:

"['Location Zero', 'Location One', 'Location Two']"

数据可以以类似的方式从服务器返回。也就是说,你可以把它变成一个对象。

var myObject = JSON.parse(myJSONString);

参见这个问题

$.ajax

Andreas建议您需要执行分配=,而不是测试是否与==相等。这是正确的,我认为你的代码不工作的原因。然而,有一种更好的方法来构建整个代码部分,使用jQuery的map函数:

$('#btnCheckout').click(function () {
    var productId = $('.ProductId').map(function () {
        return this.value;
    }).get();
    $.ajax({
        type: "POST",
        url: "functions/checkProductStock.php",
        data: {
            productId: productId
        },
        success: function (msg) {
            alert(msg);
        }
    });
});

请注意,我也使用了与Kanishka相同的技术,因此您可以访问$_POST['productId']的值。