spring mvc的controller 怎么获取ajax的数据

2025-03-06 21:49:39
推荐回答(2个)
回答1:

springmvc 中controller获取ajax数据的方法:
1、页面jsp代码:




请选择审讯室
审讯室名称


点击确定后触发ajax接口:
function setshow(){
$.ajax( {
type : "POST",
url : "<%=request.getContextPath()%>/initroom.do?method=set",
data : {
'room' : $("#roomid").find('option:selected').text(),
'roomid' :$("#roomid").val()
},
dataType: "json",
success : function(data) {
if(data.success){
alert("设置成功!");

}
else{
alert("设置失败!");
}
},
error :function(){
alert("网络连接出错!");
}
});
}
2、后台controller写法:
@RequestMapping(params = "method=set")
public void jump(HttpSession session,HttpServletRequest request, HttpServletResponse response) throws Exception{
String roomid= request.getParameter("roomid");
String room= request.getParameter("room");
session.setAttribute("ROOMID", roomid);
session.setAttribute("ROOMNAME", room);
System.out.println("session set:"+room+"=="+roomid);
response.setCharacterEncoding("utf-8");
response.getWriter().write("{\"success\":true }");
response.getWriter().flush();
}
3、springmvc 返回信息到ajax:
import com.googlecode.jsonplugin.JSONUtil;
List recordList = new ArrayList();
//获取recordlist操作省略
response.setCharacterEncoding("utf-8");
response.getWriter().write("{\"success\":true, \"data\":" + JSONUtil.serialize(recordList) + "}");
response.getWriter().flush();

回答2:

你在Controller上面也加了一个@RequestMapping("/client"),改下ajax里面url试试,你可以在ajax里面加上
success:function(data)
{
if(data == "success") {
document.location = location;
}
},
error:function()
{
alert("更新失败!");
}

ajax中data是json类型的,
要指定:
contentType : 'application/json',
dataType : 'json'
Controller中的lookfor(String etype)
应该给参数加上@RequestBody注解lookfor( @RequestBody String etype)