Javascript 在Jquery中将嵌套表单字段转换为JSON

Javascript 在Jquery中将嵌套表单字段转换为JSON,javascript,jquery,json,Javascript,Jquery,Json,尝试将表单对象作为JSON从前端JavaCScript/jquery发布到SpringMVC后端。 表单数据有一个字符串数组和其他字符串字段,如下所示 ... var cityList = []; citylist.push("SF"); citylist.push("LA"); document.forms["myForm"]["dstCities"].value = cityList; document.forms["myForm"]["dstState"].value = "CA"; ..

尝试将表单对象作为JSON从前端JavaCScript/jquery发布到SpringMVC后端。 表单数据有一个字符串数组和其他字符串字段,如下所示

...
var cityList = [];
citylist.push("SF");
citylist.push("LA");
document.forms["myForm"]["dstCities"].value = cityList;
document.forms["myForm"]["dstState"].value = "CA";
...
下面是我转换为JSON的代码

function convertFormToJSON(){
    var jsonObject = {};
    var array = $("myForm").serializeArray();

    $.each(array, function() {
        if (jsonObject[this.name] !== undefined) {
            jsonObject[this.name].push(this.value || '');
        } else {
            jsonObject[this.name] = this.value || '';
        }
    });

    jsonObject = JSON.stringify(jsonObject);
    console.log("json: " + jsonObject);
    return jsonObject;
};
投递电话:

    $.ajax({
        url: "xxx",
        type: "POST",
        data: convertFormToJSON(),
        contentType: "application/json",
        dataType: 'json',
        ...
   });
Json输出:

{"dstCities":"SF,LA", "dstState":"CA"}
但我需要它看起来像

[{"dstCities": ["SF", "LA"], "dstState":"CA"}]

您正在将数组作为值传递给:

document.forms["myForm"]["dstCities"].value = cityList;
但是浏览器在它上面使用了toString,它最终变成了连接字符串SF,LA

如果目的是将其作为字符串数组传递,则可以执行以下操作:

document.forms["myForm"]["dstCities"].value = JSON.stringify(cityList);
以这种方式,convertFormToJSON中不需要任何更改

如果城市需要显示为逗号分隔的值,则更改

   if (jsonObject[this.name] !== undefined) {
       jsonObject[this.name].push(this.value || '');
   } else {
       var value = this.value;
       if (this.name === 'dstCities') {
           value = value.split(',');
       }
       jsonObject[this.name] = value || '';
   }

看起来您的数据正在此处转换为文档。表单[myForm][dstCities].value=cityList;从数组到字符串;但这只分配了列表中的第一个城市..使用JSON.stringifycityList,它可以作为数组字符串获取,但输出现在看起来像{dstCities:[\SF\,\LA\],有什么方法可以去掉这个额外的斜杠吗