[英]How to convert form input fields to nested json structure using jquery
[英]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.