2015-09-25 71 views
0

試圖將表單對象的POST作爲JSON從前端javacsript/jquery執行到Spring MVC後端。 表單數據有一個字符串數組等串場,看起來像下面在JQuery中將嵌套的表單字段轉換爲JSON

... 
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"}] 
+0

它看起來像你的數據在這裏轉化'document.forms [「myForm會」] [「dstCities」。 value = cityList;'從數組到字符串。 – bonesbrigade

+0

我曾試過, document.forms [「myForm」] [「dstCities」] = cityList;但是,這只是分配列表中的第一個城市.. – decoder

回答

0

你傳遞一個數組作爲值:

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

使用JSON.stringify(cityList)它能夠得到數組字符串, 但輸出現在看起來像 {「dstCities」:[\「SF \」,\ 「LA \」], 任何手段來擺脫這額外的斜槓 – decoder