用json将jquery数组传递给php

时间:2011-12-23 09:18:48

标签: php jquery arrays 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方法,它应该读取页面中的所有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。 FYI应该传递的值是1和2.任何想法为什么在数组中读取和传递错误的值?或者我在上述方法中犯了错误?

3 个答案:

答案 0 :(得分:3)

这是不正确的:

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

您正在进行等级检查==而不是作业=

更改为:

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

答案 1 :(得分:1)

只需你可以做到这一点

  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);

看到这个问题

Passing JavaScript array to PHP through jQuery $.ajax

答案 2 :(得分:1)

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']