我正在尝试使用 jQuery 发布多维数组。我已经验证,在发送数组之前,它包含它应该包含的内容(通过检查特定元素并警告它们)。
但是,当我发送请求时,它会发送以下内容:
Array
(
[undefined] =>
)
这就是整个事情......
var mainArray = new Array();
$(".list").each(function(){
var day = $(this).attr("id");
var order = 1;
$("#" + id + " li").each(function(){
var subArray = new Array();
var id = $(this).attr("id");
subArray["id"] = id;
subArray["order"] = order;
subArray["day"] = day;
mainArray.push(subArray);
order++;
});
});
// This displays what I would expect
alert(mainArray[0]['id']);
alert(mainArray[1]['id']);
alert(mainArray[2]['id']);
alert(mainArray[3]['id']);
// This doesn't work
$.ajax({
type: 'post',
url: 'test2.php',
data: mainArray,
success: function(data) {
$("#test").html(data);
}
});
有什么想法吗?我的理解是 jQuery 应该自动序列化数组?
最佳答案
你的代码完全错误!
首先,为您的二维数组指定一些名称,例如项目(或任何您想要的名称)。其次,你不能使用 Array
来创建哈希(理论上你可以,但它很糟糕,jQuery 不理解这一点),你必须使用对象文字 {}
代替Array
中,仅将 Array
与数字键一起使用(使用文字 []
创建数组,而不是 new Array
) 。您的代码:
var mainArray = [];
$(".list").each(function(){
var day = $(this).attr("id");
var order = 1;
$("#" + id + " li").each(function(){
var subArray = {};
subArray["id"] = $(this).attr("id");
subArray["order"] = order;
subArray["day"] = day;
mainArray.push(subArray);
order++;
});
});
$.ajax({
type: 'post',
url: 'test2.php',
data: { items: mainArray },
success: function(data) {
$("#test").html(data);
}
});
P.S.:你可以使用$.param
(将js对象转换为查询字符串)来找出你的错误
关于javascript - jQuery AJAX,数组未序列化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13960820/