我正在尝试准备以下输入
<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个例子只是我尝试过的几个......
有人知道如何解决这个问题吗?