通过 $.post 发送多维数组
Send multidimensional Array via $.post
我有一个多维数组,我通过 $.each
填充它
$('.gBook').click(function(){
var values = [];
var valueToPush = { }; // or "var valueToPush = new Object();" which is the same
var i = 0;
$('td[data-check="true"]').each(function(){
valueToPush["price"] = $(this).attr("data-price");
valueToPush["id"] = $(this).attr("data-id");
values.push(valueToPush);
i++;
});
var arrayToSend = {values};
$.post( '<?php echo PATH;?>ajax/updateRoom.php',values, function(data){
if(data != "ERROR"){
$('#all-content').html(data).css("overflow-y","auto");
}else{
alert("ERROR");
}
});
});
但是所有 POST 变量的结果都是一样的:
Array (
[values] => Array (
[0] => Array ( [price] => 15 [id] => 3380 )
[1] => Array ( [price] => 15 [id] => 3380 )
[2] => Array ( [price] => 15 [id] => 3380 )
)
)
我的错误在哪里?似乎 "push" 每次都会覆盖?
这一行:
var valueToPush = { };
在你的循环之外。
所以你:
- 创建一个对象
- 在
valueToPush
中引用它
- 在其中输入值
- 将对它的引用复制到数组中
- 转到 3
你只有一个对象,你只是在数组中有多个对它的引用。
每次循环时都需要创建一个新对象。
$('td[data-check="true"]').each(function(){
var valueToPush = {};
valueToPush["price"] = $(this).attr("data-price");
你的每个循环应该看起来像这样:
$('td[data-check="true"]').each(function(){
values.push({
price: $(this).attr("data-price"),
id: $(this).attr("data-id")
});
});
您需要在每次迭代中插入一个新对象。目前您正在将对单个对象的引用插入到数组中。
我有一个多维数组,我通过 $.each
填充它$('.gBook').click(function(){
var values = [];
var valueToPush = { }; // or "var valueToPush = new Object();" which is the same
var i = 0;
$('td[data-check="true"]').each(function(){
valueToPush["price"] = $(this).attr("data-price");
valueToPush["id"] = $(this).attr("data-id");
values.push(valueToPush);
i++;
});
var arrayToSend = {values};
$.post( '<?php echo PATH;?>ajax/updateRoom.php',values, function(data){
if(data != "ERROR"){
$('#all-content').html(data).css("overflow-y","auto");
}else{
alert("ERROR");
}
});
});
但是所有 POST 变量的结果都是一样的:
Array (
[values] => Array (
[0] => Array ( [price] => 15 [id] => 3380 )
[1] => Array ( [price] => 15 [id] => 3380 )
[2] => Array ( [price] => 15 [id] => 3380 )
)
)
我的错误在哪里?似乎 "push" 每次都会覆盖?
这一行:
var valueToPush = { };
在你的循环之外。
所以你:
- 创建一个对象
- 在
valueToPush
中引用它
- 在其中输入值
- 将对它的引用复制到数组中
- 转到 3
你只有一个对象,你只是在数组中有多个对它的引用。
每次循环时都需要创建一个新对象。
$('td[data-check="true"]').each(function(){
var valueToPush = {};
valueToPush["price"] = $(this).attr("data-price");
你的每个循环应该看起来像这样:
$('td[data-check="true"]').each(function(){
values.push({
price: $(this).attr("data-price"),
id: $(this).attr("data-id")
});
});
您需要在每次迭代中插入一个新对象。目前您正在将对单个对象的引用插入到数组中。