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:

/**
 * @author fengzp
 * @date 16/12/15下午6:08
 * @email fengzp@gzyitop.com
 * @company 广州易站通计算机科技有限公司
 */
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;
    }
}

之前使用@RequestBody接收json数据总是报400或者415,今天终于把它搞成功了,在这里记录一下。

posted @ 2016-12-15 21:06  fengzp  阅读(28167)  评论(0编辑  收藏  举报