簡體   English   中英

在Jquery中將嵌套的表單字段轉換為JSON

[英]Convert nested form fields to JSON in Jquery

嘗試從前端javacsript / jquery到Spring MVC后端以JSON形式對JSON對象進行POST。 表單數據具有一個字符串數組和其他字符串字段,如下所示

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

POST電話:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM