后端使用如下方式接收前端传入参数:
1 @PostMapping(value = "/test", produces = MediaType.APPLICATION_JSON_UTF8_VALUE) 2@ResponseBody 3 public Map<String, Object> test(@RequestBody Map<String, Object> map) { 4 System.out.println(map); 5 return map; 6 }
由于使用了 @RequestBody 注解,所以,前端需要传递 JSON 数据。那么,如何将表单数据快速转换为 JSON 字符串呢?
定义如下通用方法:
1 function serializeForm(form){ 2 var obj = {}; 3 $.each(form.serializeArray(),function(index){ 4 if(obj[this['name']]){ 5 obj[this['name']] = obj[this['name']] + ','+this['value']; 6 } else { 7 obj[this['name']] =this['value']; 8 } 9 }); 10 return obj; 11 }
以上方法会返回一个 Object,然后再通过 JSON.stringify(obj) 将 JSON 对象转换为 JSON 字符串即可。
调用 serializeForm() 方法只需要传入 表单对象即可,如: serializeForm($('form'));
<form action="" method="POST" >
userName: <input type="text" name="userName" /><br /> password: <input type="password" name="password" /><br />
<input type="button" value="Submit" />
</form>
<script>
$(function() {
$('#btn').click(function () {
var jsonObj = serializeForm($("form"));
var jsonStr = JSON.stringify(jsonObj);
$.ajax({
type: 'POST',
url: 'http://localhost:8083/test',
data: jsonStr,
headers: {
'Content-Type': 'application/json;charset=UTF-8'
},
success: function (data) {
alert("success: " + data);
},
error: function (data) {
alert("error: " + data);
}
});
return false;
});
});
function serializeForm(form){
var obj = {};
$.each(form.serializeArray(),function(index){
if(obj[this['name']]){
obj[this['name']] = obj[this['name']] + ','+this['value'];
} else {
obj[this['name']] =this['value'];
}
});
return obj;
}
</script>