ajax怎么获取controller数据

2024-12-03 00:58:33
推荐回答(1个)
回答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();