在jQuery中序列化数组 [英] Serializing an array in jQuery
问题描述
如何为$.ajax
提交准备元素数组?
How to prepare an array of element for $.ajax
submit?
此处图像返回["val1","val2"]
,但是使用$.param(images)
后,我得到以下信息:
Here images return ["val1","val2"]
, but after I use $.param(images)
I get the following:
undefined = undefined& undefined = undefined
undefined=undefined&undefined=undefined
这是我的代码:
Here is my code:
$('#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脚本.
Generally the idea is to check the images to delete on the page, then on a button click loop trough all images checked and serialize an array for submit over AJAX to the PHP script.
推荐答案
您没有将正确格式的数组传递给$.param
.从 jQuery.param
文档:
You're not passing an array in proper format to $.param
. From the jQuery.param
docs:
如果传递的对象在数组中,则它必须是
.serializeArray()
返回的格式的对象数组
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
均未定义.它应该看起来像这样:
The array should be an array of objects consisting of name/value pairs. You see undefined=undefined&undefined=undefined
because "val1".name
, "val1".value
, "val2".name
, and "val2".value
, are all undefined. It should look something like this:
[{name: 'name1', value: 'val1'}, {name: 'name2', value: 'val2'}]
因此,您可以像这样构造数组(假设您的复选框具有name
属性):
So you can construct the array like this (assuming your checkboxes have a name
attribute):
$('#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;
});
尽管如此,即使使用slicker也是因为 .map()
(因为函数式编程是好东西):
Even slicker, though, is to use .map()
(because functional programming is good stuff):
$('#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中序列化数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!