【问题标题】:pass jquery array to php with json使用 json 将 jquery 数组传递给 php
【发布时间】: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 会更有用。

标签: php jquery arrays json


【解决方案1】:

这是不正确的:

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

您正在执行相等性检查 == 而不是赋值 =

改为:

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

【讨论】:

  • 感谢我现在让这项工作向前迈进了一步!....正在发布的参数是:productId[] 2 productId[] 1 来源显示此productId%5B%5D=2&amp;productId%5B%5D=1
【解决方案2】:

你可以这样做

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

可以以类似的方式从服务器返回数据。 IE。你可以把它变回一个物体。

var myObject = JSON.parse(myJSONString);

看到这个问题

Passing JavaScript array to PHP through jQuery $.ajax

【讨论】:

    【解决方案3】:

    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'] 访问这些值。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-11-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-25
      • 2015-08-21
      • 1970-01-01
      • 2012-06-01
      相关资源
      最近更新 更多