简体   繁体   中英

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. 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,

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:

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

Json output:

{"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"

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.


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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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