gpt4 book ai didi

jquery - 在 jQuery 中序列化数组

转载 作者:行者123 更新时间:2023-12-03 22:03:02 24 4
gpt4 key购买 nike

如何为$.ajax提交准备元素数组?

此处图像返回["val1","val2"],但在使用$.param(images)后,我得到以下结果:

undefined=undefined&undefined=undefined


这是我的代码:

$('#rem_images').click(function() {
var images = new Array();
$('.images_set_image input:checked').each(function(i) {
images[i] = $(this).val();
});
alert($.param(images));

return false;
}


一般来说,想法是检查页面上要删除的图像,然后在按钮上单击循环检查所有图像并序列化数组以通过 AJAX 提交到 PHP 脚本。

最佳答案

您没有将正确格式的数组传递给$.param。来自 jQuery.param docs :

If the object passed is in an Array, it must be an array of objects in the format returned by .serializeArray().

该数组应该是由名称/值对组成的对象数组。您会看到 undefined=undefined&undefined=undefined 因为 "val1".name, "val1".value, "val2".name"val2".value 均未定义。它应该看起来像这样:

[{name: 'name1', value: 'val1'}, {name: 'name2', value: 'val2'}]

因此,您可以像这样构造数组(假设您的复选框具有 name 属性):

$('#rem_images').click(function(){
var images = [];
$('.images_set_image input:checked').each(function(){
var $this = $(this);
images.push({name: $this.attr('name'), value: $this.val()});
});
alert($.param(images));
return false;
});

不过,更巧妙的是使用 .map() (因为函数式编程是好东西):

$('#rem_images').click(function(){
var images = $('.images_set_image input:checked').map(function(){
var $this = $(this);
return {name: $this.attr('name'), value: $this.val()};
}).get();
alert($.param(images));
return false;
});

关于jquery - 在 jQuery 中序列化数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4239460/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com