SpringMvc+ajax realizes data transfer in json format


Pass JSON object

front end

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',
    });
}

rear end

Controller:

@RequestMapping(value = "userRole", method = RequestMethod.POST)
@ResponseBody
public List<Role> selectRoles(String username) throws WebTransException {
    
    /* 逻辑代码 */

}

Pass JSON string + @RequestBody receive

front end

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);
        }
    });
    
}

rear end

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;
    }
}

Before using @RequestBody to receive json data, it always reported 400 or 415. Today I finally succeeded in it, and record it here.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325806911&siteId=291194637