我正在尝试使用 jQuery 加载在 while 循环内将 PHP 中单个表单的数据发布到另一个页面。目前,当我查看输出时,仅提交第一个结果。当我单击其余表单时,它会不断刷新页面。如何使所有表单都能从我的 PHP 页面发布唯一数据?
这是我的 PHP 脚本:
while (mysqli_stmt_fetch($select_product)): ?>
<div class="col-md-4 top_brand_left" style="margin-top:40px;">
<div class="hover14 column">
<div class="tm_top_brand_left_grid">
<div class="tm_top_brand_left_grid_pos">
</div>
<div class="tm_top_brand_left_grid1">
<figure>
<div class="snipcart-item block">
<div class="snipcart-thumb">
<a href="javascript:void(0)"><img class="lazy" title="" alt="" src="/web/images/spinner.gif" data-original="/web/images/<?php echo $product_image; ?>"></a>
<p><?php echo htmlentities($product_name); ?></p>
<h4><?php echo "₦".$product_price; ?><span></span></h4>
</div>
<div class="snipcart-details top_brand_home_details">
<form id="addToCart" method="post">
<fieldset>
<input type="hidden" name="id" id="id" value="<?php echo htmlentities($product_id); ?>">
<input type="submit" id="add_to_cart" name="add_to_cart" value="Add to cart" class="button">
</fieldset>
</form>
</div>
</div>
</figure>
</div>
</div>
</div>
</div>
<?php endwhile; ?>
这是我的 jQuery 脚本:
$("#addToCart").submit(function(event){
event.preventDefault();
var page = $("#page").val();
var id = $("#id").val();
var cat_id = $("#cat_id").val();
var res_name = $("#res_name").val();
var add_to_cart = $("#add_to_cart").val();
$("#feedback").load("/web/cart.php", {
page:page,
id: id,
cat_id: cat_id,
res_name: res_name,
add_to_cart: add_to_cart
});
});
最佳答案
更改 PHP 循环中类的所有 id。
然后单击,查找最接近的 .column
以查找相关元素。
$(".addToCart").submit(function(event){
event.preventDefault();
var column = $(this).closest(".column");
var page = column.find(".page").val();
var id = column.find(".id").val();
var cat_id = column.find(".cat_id").val();
var res_name = column.find(".res_name").val();
var add_to_cart = $(this).val();
$("#feedback").load("/web/cart.php", { // This element is outside the PHP loop and has a unique id.
page:page,
id: id,
cat_id: cat_id,
res_name: res_name,
add_to_cart: add_to_cart
});
});
关于javascript - 在 while 循环中从一种表单发布数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51574682/