ajax发送post/get 数据,java后台如何接收

  • Post author:
  • Post category:java


//表单键值对post提交

var paramData={


roomId:’1′,

address:’2′

};

$.ajax({


url:”/test”,

type:”post”,

contentType:’application/x-www-form-urlencoded;charset=utf-8′,

data: paramData,

success:function(result){


console.log(“result=”+JSON.stringify(result));

}

});

@RequestMapping(value=”/test”, method={RequestMethod.POST,RequestMethod.GET})

public @ResponseBody RestfulResult test(HttpServletRequest request,HttpServletResponse response){


RestfulResult result=new RestfulResult(StatusCode.OK);

String roomId=request.getParameter(“roomId”);

String address=request.getParameter(“address”);

System.out.println(“roomId:”+roomId);

System.out.println(“address:”+address);

return result;

}

//json字符串 post提交

$.ajax({


url:”/test1″,

type:”post”,

contentType:’application/json;charset=utf-8′,

data: JSON.stringify(paramData),

success:function(result){


console.log(“result=”+JSON.stringify(result));

}

java 代码,方法1:

@RequestMapping(value=”/ammeterMon/test1″, method={RequestMethod.POST})

public @ResponseBody RestfulResult test1(@RequestBody JSONObject obj){


RestfulResult result=new RestfulResult(StatusCode.OK);

System.out.println(“data:”+obj);

String roomId=obj.getString(“roomId”);

String address=obj.getString(“address”);

System.out.println(“roomId:”+roomId);

System.out.println(“address:”+address);

return result;

}

java 代码,方法2:

public class Room {


private int roomId;

private String address;

public int getRoomId() {


return roomId;

}

public void setRoomId(int roomId) {


this.roomId = roomId;

}

public String getAddress() {


return address;

}

public void setAddress(String address) {


this.address = address;

}

}

@RequestMapping(value=”/test2″, method={RequestMethod.POST})

public @ResponseBody RestfulResult test2(@RequestBody Room room){


RestfulResult result=new RestfulResult(StatusCode.OK);

Integer roomId=room.getRoomId();

String address=room.getAddress();

System.out.println(“roomId:”+roomId);

System.out.println(“address:”+address);

return result;

}



版权声明:本文为xzb90原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。