向使用$. serializearray()检索的数组中添加数组值

Adding an array value to an array retrieved using $.serializeArray()

本文关键字:数组 添加 检索 serializearray      更新时间:2023-09-26

有复选框,属于表单A:

<input type="checkbox" class="item-selector" name="item[]" value="1" />
<input type="checkbox" class="item-selector" name="item[]" value="2" />
<input type="checkbox" class="item-selector" name="item[]" value="3" />
<!-- etc. -->

然后我有表单B,需要表单A的复选框值。表单A也可能有其他输入字段,但我对这些不感兴趣。我只关心$('input.item-selector')。我是这样写的:

var postData = $('#form-a').serializeArray();
var items = $('.item-selector:checked').map(function(){
    return this.value;
}).get();
if(items.length > 0) {
    postData.push({name: 'itemId', value: items});
}

但是这种向postData添加东西的方式似乎不起作用,因为我发送表单的PHP脚本找不到itemId。有趣的是,这确实有效:

postData.push(name: 'aName', value: 'notAnArrayButAStringValue');

我也尝试了一些像这样的解决方案:http://benalman.com/projects/jquery-misc-plugins/#serializeobject但他们的问题是,虽然他们工作得很好,但出于某种原因,如果在表格B中有复选框,表格B的复选框值被错误地解析,导致空值和数据丢失。它看起来像这样:

var postData = $(this.form).serializeObject();    
var items = $('.item-selector:checked').map(function(){
    return this.value;
}).get();
if(items.length > 0) {
    postData.itemId = items;
}

使用JSON。Stringify显示对象结构是这样的:

{
    "name":"Simon J. Kok",
    "address_id":"39669",
    "email":"*****",
    "content_id":"21921",
    "client_id":"42101",
    "is_ebill":["","1"], <-- this is a checked checkbox
    "is_banned":"", <-- this is an unchecked checkbox
    "button":"save"
}

表单B中的复选框看起来像

<input type="checkbox" value="1" name="is_ebill" />
<input type="checkbox" value="1" name="is_banned" />

所以我需要的是关于如何将复选框从形式A添加到$.serializeArray()结果数组的一些见解-或-一种解决使用Ben Alman插件时返回数组的复选框问题的方法。

这是一种方法。首先,它需要form-b中的隐藏字段:

<input type="hidden" id="itemId" name="itemId" value="" />

在提交表单时将使用item-selector数据填充:

$('#form-b').on('submit', function() {
    var checkedValues = [];
    $('.item-selector:checked').each(function() {
        checkedValues.push($(this).val());
    });
    $('#itemId').val(checkedValues.join(','));
    console.debug('Form B data:', $('#form-b').serializeArray());
});

调整语法以适应您的习惯用法。下面是一个示例:

http://jsfiddle.net/klenwell/12evxfvc/

实际上我已经回答了我自己的问题。我使用JSON.Stringify来输出$.serializeArray()返回的JSON格式字符串,并且很明显该结构需要工作。下面是如何将数组值逐个添加到使用$.serializeArray():

检索的数组中
var items = $('.item-selector:checked').map(function(){
    return this.value;
}).get();
$.each(items, function(i, v){
    postData.push({name: 'itemId[]', value: v});
});