SpringMvc+ajax 实现json格式数据传递:
传JSON对象
前 端
function test () {
var param = {username : "yitop"};
$.ajax({
timeout : 20000,
type : "POST",
dataType : "JSON",
url : "/user/userRole.htm",
data : param,
success : function(data){
alert(data);
}
//注意:这里不能加下面这行,否则数据会传不到后台
//contentType:'application/json;charset=UTF-8',
});
}
后端
Controller:
@RequestMapping(value = "userRole", method = RequestMethod.POST)
@ResponseBody
public List<Role> selectRoles(String username) throws WebTransException {
/* 逻辑代码 */
}
传JSON字符串+@RequestBody接收
前端
function icheckDelete(url){
var parms = {
list : array //这是个数组
};
$.ajax({
dataType: "JSON",
contentType:'application/json;charset=UTF-8',//关键是要加上这行
traditional:true,//这使json格式的字符不会被转码
data: JSON.stringify(parms),
type: "DELETE",
timeout: 20000,
url: url,
success : function () {
alert("删除成功!");
},
error : function (data){
alert(data.responseText);
}
});
}
后端
Controller:
@RequestMapping(value = "deleteList", method = RequestMethod.DELETE)
@ResponseBody
public String delete(@RequestBody DeleteListRequest request) throws WebTransException{
/* 逻辑代码 */
return "success";
}
DeleteListRequest:
public class DeleteListRequest {
List<Map<String, String>> list = new ArrayList<>();
public DeleteListRequest() {
}
public List<Map<String, String>> getList() {
return list;
}
public void setList(List<Map<String, String>> list) {
this.list = list;
}
}