Ajax+SpringMVC requestBody

前端之家收集整理的这篇文章主要介绍了Ajax+SpringMVC requestBody前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

ajax+Spring MVC
经验证,上文写的是比较正确的,所以转过来保存一下.

传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;
    }
}
原文链接:https://www.f2er.com/springmvc/160579.html

猜你在找的SpringMVC相关文章