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

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了spring mvc的controller 怎么获取ajax的数据相关的知识,希望对你有一定的参考价值。

springmvc 中controller获取ajax数据的方法:
1、页面jsp代码:
<table style="width: 100%" class="table" cellspacing="1" cellpadding="1" border="0">
<tr><td class="ti1" colSpan="2">请选择审讯室</td></tr>
<tr><td class="ti2hui">审讯室名称</td><td class="ti1cu">
<select id="roomid" name="roomid" >
<c:forEach items="$roomlist" var="room">
<option value ="$room.id">$room.name</option>
</c:forEach>
</select>
</td></tr>
<tr><td class="ti2hui" colSpan="2" align="center"><input type="button" onclick="setshow()" value="确定"/> </td></tr>
</table>
点击确定后触发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<Records> recordList = new ArrayList<Records>();
//获取recordlist操作省略
response.setCharacterEncoding("utf-8");
response.getWriter().write("\\"success\\":true, \\"data\\":" + JSONUtil.serialize(recordList) + "");
response.getWriter().flush();
参考技术A 你在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)本回答被提问者采纳

以上是关于spring mvc的controller 怎么获取ajax的数据的主要内容,如果未能解决你的问题,请参考以下文章

spring3 mvc 中怎么从当前action跳到另一个action中

spring mvc中,我只想获得数据,不想跳转,controller该怎么写?

spring mvc怎么返回json

spring mvc controller实现原理

spring mvc swagger no operations defined in spec,怎么解决

Spring MVC @Controller中转发或者重定向到其他页面的信息怎么携带和传递(Servlet API对象)HttpServletRequestHttpServletRespose