通过Ajax传递几个PHP动态变量

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (1)
  • 关注 (0)
  • 查看 (107)

有一个动态生成的表,它显示了一种购物列表,其中包含了一些数据,比如从API获得的产品名称和产品价格。

当我单击“购物”按钮时,我想要一个显示总结购买的文本的模式,并单击“确认”按钮将数据保存到DB中。

在这种情况下,我将动态变量存储在元素id或值中,或者两者都存储。但是,如果我想-就像现在一样-存储两个以上的变量,该怎么办?

<tbody>

            <?php

            foreach ($result as $doc) {

              $price = $doc['2. price'];
              $name = $doc['1. symbol'];
              $rd_price = round($price, 2);
              ?>

              <tr>
                  <td><?php echo $name; ?></td>
                  <td class="product_price"><?php echo $rd_price; ?></td>
                  <td><input type="text" id= "product_qty_" name="qty" class="product_qty" value="0"></td>
                  <td class="amount_sub_total">0</td>
                  <td><button class="sbtn" data-toggle = "modal" data-target = "#myModal" id="<?php echo $name; ?>" value="<?php echo $rd_price; ?>" onclick="showDetails(this)">
                     <i class="fas fa-shopping-cart"></i>
                  </button></td>
              </tr>

        <?php } ?>

</tbody>

这是我的JS

function showDetails(button) {
var customerNumber = button.id;
var customerPrice = button.value;
var selectedAmount = product_quantity;

    $.ajax({
    url: "customer.php",
    method: "GET",
    data: {"customerNumber": customerNumber, "customerPrice": customerPrice, "selectedAmount": selectedAmount},
    success: function(response){
      $("#value").text(response);
    }
});

}

这导致了这个customer.php:

<?php
$customerNumber = $_GET["customerNumber"];
$customerPrice = $_GET["customerPrice"];
$selectedAmount = $_GET["selectedAmount"];
$totalprice = $customerPrice * $selectedAmount;

echo "You are about to purchase " . $selectedAmount . " units of " . $customerNumber . " at $ " . $customerPrice . " per unit. " . "Total price: $ " . $totalprice .  " Do you want to proceed?";

 ?>

但是,如果我需要存储两个以上的值,或者只想留下一个非变量ID,我该如何做呢?

提问于
用户回答回答于

只需将它们作为attr添加到这样的元素中即可。

<button data-id="id" data-amount="amount" data-price="price"> send</button>

JS

function showDetails(button) {
var customerNumber = $(this).attr("data-id");
var customerPrice = $(this).attr("data-price");
var selectedAmount = $(this).attr("data-amount");

    $.ajax({
    url: "customer.php",
    method: "GET",
    data: {"customerNumber": customerNumber, "customerPrice": customerPrice, "selectedAmount": selectedAmount},
    success: function(response){
      $("#value").text(response);
    }
});

别忘了传递给函数$(this)this

扫码关注云+社区

领取腾讯云代金券