0

我正在尝试准备以下输入

<input type="text" name="customer[firstname]">
<input type="text" name="customer[surename]">
<input type="text" name="customer[cuid]">

在 ajax 函数中使用它们以使用 PHP 验证它们。我将收到的数组应如下所示$data['customer']['firstname']

这是我的第一次尝试

$.each($('input[name^="customer"]').serializeArray(), function() {
    data[this.name] = this.value;
});

问题:请求中的数组看起来$data["[customer[firstname]"]并不漂亮,我将有不同的键,例如 product[...]、order[...]。然后我需要“客户”作为单独的键。

然后我考虑删除并替换括号,并在发送之前创建我自己的数组。但是问题比我想象的要多...

var data = {};

$.each($('input[name^="customer"]').serializeArray(), function() {
    let name = this.name.replace( ']', '' ).replace( '[', ',' ).split(',')[1];
    data['customer'].push({[name] : this.value}); // <- Error: push is not a function
    data = { 'customer' : {[name] : this.value} }; // <- Problem: data gets overwritten with the next key:value
    data['customer'][name] = this.value; // <- Error: `customer` not defined
});

这3个例子只是我尝试过的几个......

有人知道如何解决这个问题吗?

4

1 回答 1

1

现在它可以正常工作了。请检查一下。

var data = { customer: [] }; 
$.each($('input[name^="customer"]').serializeArray(), function() {
     var new_name = this.name.replace("customer[", "");
         new_name = new_name.replace("]", "");
         data['customer'].push(new_name);
         data['customer'][new_name] = this.value;
  });
于 2020-01-16T05:39:53.783 回答