You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将jQuery序列化表单数组转为指定结构JSON用于AJAX提交?

把表单序列化结果转成目标JSON结构的最简方法

我懂你现在的需求——用serializeArray()得到的是一堆带name和value的小对象数组,但你需要把这些字段直接整合成一个键值对对象,再放进数组里对吧?

最简的实现方式就是用数组的reduce方法快速转换,核心逻辑几行就能搞定:

$('#create').click(function(event) {
 console.log('Create Button Click');
 // 核心转换逻辑
 var transformedData = [$('#customer_form').serializeArray().reduce((acc, item) => {
  acc[item.name] = item.value;
  return acc;
 }, {})];
 var dataJSON = JSON.stringify(transformedData);
 console.log(dataJSON);
 $.ajax({
 type: "POST",
 url: "/customer/",
 data: dataJSON,
 contentType: "application/json; charset=utf-8",
 dataType: "json",
 success: function(data){
 console.log('Success');
 console.log(data);
 },
 failure: function(errMsg) {
 console.log('Error');
 console.log(errMsg);
 }
 });
 event.preventDefault();
});

要是你偏好更简洁的ES6写法,还能把转换逻辑压缩成一行:

var transformedData = [$('#customer_form').serializeArray().reduce((acc, item) => ({...acc, [item.name]: item.value}), {})];

原理很直白:reduce会遍历serializeArray返回的每一项,把每个字段的name作为对象的键,value作为对应的值,逐步合并到初始的空对象{}里,最后把合并好的对象放进数组,再转成JSON字符串,就完全匹配你想要的结构了。

要是你习惯用jQuery的each方法,也可以这么写,逻辑更直观:

var formObj = {};
$('#customer_form').serializeArray().each(function() {
  formObj[this.name] = this.value;
});
var dataJSON = JSON.stringify([formObj]);

不管用哪种方式,最终生成的JSON结构都会是你需要的:

[{"name": "n", "address_line_1": "a1", "address_line_2": "a2", "town": "t", "postal_code": "p", "region": "r", "phone_1": "p", "phone_2": "pa", "fax": "f", "email":"e", "web": "w"}]

内容的提问来源于stack exchange,提问作者M.E.

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 07:38:20