如何使用javascript或jquery post方法从循环发送变量并使用php接收



我想显示所有表值,然后使用 javascript post menthod 在另一个 php 页面上发送和接收它们,但似乎我的代码只能将表列表中的一个项目发送到另一个 php 页面。

<form  class="commerce" id='commence'>
<input type='text' id='shop' value='' class='form-wrapper'>
<?php
$check = "SELECT * FROM tbl_products ";
$checks = mysqli_query($db, $check);
while ($found = mysqli_fetch_array($checks)) {
$id = $found['id'];
$amount = $found['amount'];
$price = $found['price'];
echo"<input type='text' id='product' value='$id' class='form-wrapper'>
<input type='text' id='stock' value='$amount' class='form-wrapper'>
<input type='text' id='price' value='$price' class='form-wrapper'>";
}
?>
<button type='button' class='prisoner_entry '  >SAVE</button>
</form>
<script type="text/javascript">
$(document).on("click", ".prisoner_entry", function () {
var fname = document.getElementById("shop").value;
var product = document.getElementById("product").value;
var stock = document.getElementById("stock").value;
var price = document.getElementById("price").value;
$.ajax({
type: 'POST',
url: "data.php",
data: {
fullname: fname, productname: product, stocknumber: stock, itemprice: price},
success: function (result) {
}
});
});
</script>
<?php
if(isset($_POST['fullname'])){
$fullname = mysqli_real_escape_string($db,$_POST["fullname"]);      
$productname = mysqli_real_escape_string($db,$_POST["productname"]);  
$stocknumber =mysqli_real_escape_string($db,$_POST["stocknumber"]);       
$itemprice =mysqli_real_escape_string($db,$_POST["itemprice"]);      
$rphone = mysqli_real_escape_string($db,$_POST["rephone"]);     
}   
?>

您正在创建具有相同id的多个元素。 每个id每页都应该是唯一的。 您应该将它们更改为class并以这种方式检索我。

.PHP

echo "<input type='text' class='product form-wrapper' value='$id' />
...

.JS

const form = document.querySelector('#commence');
const products = form.querySelectorAll('.product');
const stocks = form.querySelectorAll('.stock');
const prices = form.querySelectorAll('.price');
const shopItems = [];
for (let i = 0; i < products.length; i++) {
$.ajax({
type : 'POST',
url : "data.php",
data : {
productName: products[i].value,
stockNumber: stocks[i].value,
itemPrice: price[i].value
},
});
}

我通常完成此操作的方法是将变量附加到 ajax 请求的数据中,如下所示:

data: $(this).serialize() + '&action=query',

$(this).serialize()是"我的 Web 表单"中的数据

&是如何区分要传递的变量。

第一部分action=是我将用于从 PHP 中的 GET/POST 变量检索数据的名称。

最后,query是我传递的数据。

因此,在您的情况下,您可以执行以下操作:

data: someData + '&fname='+fname....等等。

要记住的最重要的事情是,如果没有名称,您将无法访问 PHP 中 GET/POST 变量中的对象。