简体   繁体   English

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

[英]Convert nested form fields to JSON in Jquery

Trying to do POST of Form object as JSON from front end javacsript/jquery to Spring MVC backend. 尝试从前端javacsript / jquery到Spring MVC后端以JSON形式对JSON对象进行POST。 Form data has a string array and other string field, looks like below 表单数据具有一个字符串数组和其他字符串字段,如下所示

...
var cityList = [];
citylist.push("SF");
citylist.push("LA");
document.forms["myForm"]["dstCities"].value = cityList;
document.forms["myForm"]["dstState"].value = "CA";
...

Below is my code for converting to JSON, 以下是我转换为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;
};

POST call: POST电话:

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

Json output: Json输出:

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

But I need it to look like 但我需要它看起来像

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

You are passing an array as value to : 您正在将数组作为值传递给:

document.forms["myForm"]["dstCities"].value = cityList;

but the browser is using toString() on it and it ends up as joined string "SF,LA" 但是浏览器在上面使用toString() ,最终以连接字符串"SF,LA"

If the intent is to pass it as string array can do: 如果意图是将其作为字符串数组传递,则可以执行以下操作:

document.forms["myForm"]["dstCities"].value = JSON.stringify(cityList);

No changes would be needed in convertFormToJSON this way. 这样,无需在convertFormToJSON中进行任何更改。


If the cities need to be displayed as comma separated values then change 如果需要将城市显示为逗号分隔的值,请更改

   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 || '';
   }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM