如何使用Ajax和其他非数组数据将JavaScript数组发送到PHP脚本? [英] How can I send a javascript array to a PHP script using Ajax along with other non-array data?
问题描述
我有一个网站,用户可以在其中订购商品.我目前正在向PHP脚本发送各种信息,以便可以从那里将它们添加到数据库中:
I have a site where users can order items. I am currently sending various bits of information to the PHP script so they can be added to the database from there:
$.ajax ({
type: "POST",
url: "./pay.php",
dataType: "json",
data: {
"firstName" : firstName,
"lastName" : lastName,
"email" : email,
"price" : price
}
});
这很好.现在,我想发送两个包含ID和已订购产品数量的数组.由于我不知道给定时间点有多少个产品或它们的ID是什么,因此无法像上面所做的那样将它们添加为单独的项目.目前,我在单独的数组中具有产品ID及其对应的数量,例如:
This is working well. Now I would like to send over two arrays that contain the id's and quantities of products that were ordered. Since I don't know how many products there are at any given point or what their id is, I cannot add them as individual items as I have done above. Currently I have the product ID's and their corresponding quantities in separate arrays as such:
productIds: ["6", "1"]
quantities: ["1", "4"]
我想将这些数组与其余变量一起发送到PHP脚本,以便我可以遍历这些数组并将信息插入数据库中.
I would like to send these arrays to the PHP script along with the rest of the variables so I can loop through those arrays and insert the information into the database.
我可以这样吗?
$.ajax ({
type: "POST",
url: "./pay.php",
dataType: "json",
data: {
"firstName" : firstName,
"lastName" : lastName,
"email" : email,
"price" : price,
"productIds" : productIds,
"quantities" : quantities
}
});
我目前可以在PHP脚本中像这样访问非数组变量:
The non-array variables I am currently able to access like this in the PHP script:
$email = $_POST['email'];
$firstName = $_POST['firstName'];
$lastName = $_POST['lastName'];
$price = $_POST['price'];
我想像这样在PHP脚本中循环遍历productIds数组,但是我想我缺少了一些东西:
I would like to loop through the productIds array in the PHP script something like this, but I think I am missing something:
$i = 1;
foreach ($_POST['productIds'] as $value) {
$sql = 'INSERT INTO orders SET
product_id = "'.$_POST['productIds'][$i].'",
quantity = "'.$_POST['quantities'][$i].'"';
$result = $conn->query($sql);
$i++;
}
如何使用Ajax和其他非数组数据将JavaScript数组发送到PHP脚本?
How can I send a javascript array to a PHP script using Ajax along with other non-array data?
推荐答案
只需将数组传递给data参数
Just pass the arrays to the data parameter
var productIds = ["6", "1"];
var quantities = ["1", "4"];
$.ajax ({
type: "POST",
url: "./pay.php",
dataType: "json",
data: {
"firstName" : firstName,
"lastName" : lastName,
"email" : email,
"price" : price,
"productIds": productIds,
"quantities": quantities
}
});
这篇关于如何使用Ajax和其他非数组数据将JavaScript数组发送到PHP脚本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!