您的位置:首页 > Web前端 > JQuery

jquery post json

2015-10-27 11:53 567 查看
jquery ajax调用,有的情况下提交的参数比较多,这时我们希望将这些参数作为一个json对象传递到controller中进行处理,那么就需要使用到post json对象的功能,下面的例子简单说明这个功能的使用。

js代码,需要注意contentType:”application/json”,不然会出现415的错误

<script type="text/javascript">
$(function(){
var para = {
name : 'lpn',
cname : 'shine'
};

var jsonpara = $.toJSON(para);

$("#checkName").click(function(){
$.ajax({
url : webContextPath + "/main/checkName",
async : true,
type : "POST",
contentType : "application/json",
dataType : "json",
data : jsonpara,
success : function(response) {
var errorInfo = response.errorInfo;
if (errorInfo != null) {
$("#checkInfo").html(errorInfo);
} else {
$("#checkInfo").html("name is available");
}
},
error : function() {
alert("server exception");
}
});
});
});
</script>


controller代码,需要注意@RequestBody的使用,它和@ResponseBody的作用一样,都是数据json处理

@ResponseBody
@RequestMapping(value = "/checkName", method = RequestMethod.POST)
public Map<String, Object> checkName(@RequestBody CheckNameParam checkNameParam) {
System.out.println(checkNameParam.toString());
Map<String, Object> jsonMap = new HashMap<String, Object>();
return jsonMap;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: