(1)简单交互:
<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-----提交的参数可以通过url提交,也可以用data:{}方式提交-------------------------------
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("网络连接出错!"); } }); }
------------------------spring mvc-------------------------------------------------
@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(); }
(2)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();
-------------------------------ajax处理序列化对象--------------------------------------------
var text = ‘‘; $(data.data).each(function() { text = text + ‘<li onclick="selectRecord(‘ + this.id + ‘)" style="cursor: pointer; height:20px; list-style:none; valign: center;line-height:23px;"><div style="float:left; width:15px; height:20px; background:url(Images/record_icon.png) no-repeat center;"></div>‘ + this.name + ‘</li>‘; }); $(‘#recordDiv‘).html(text);
(3)最先进的做法:
在 Spring mvc3中,响应、接受 JSON都十分方便。
使用注解@ResponseBody可以将结果(一个包含字符串和JavaBean的Map),转换成JSON。
使用 @RequestBody 注解前台只需要向 Controller 提交一段符合格式的 JSON,Spring 会自动将其拼装成 bean。
Spring这个转换是靠org.codehaus.jackson这个组件来实现的,所有需要引入jackson-core-asl和org.codehaus.jackson两个jar包
Html代码 <title>Spring MVC</title> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script> <script type="text/javascript" src="http://jquery-json.googlecode.com/files/jquery.json-2.2.min.js"></script> <script type="text/javascript" src="<%=request.getContextPath()%>/scripts/user/index.js"></script> </head> <body> <div id="info"></div> <form action="add" method="post" id="form"> 编号:<input type="text" name="id"/> 姓名:<input type="text" name="username"/> 年龄:<input type="text" name="age"/> <input type="button" value="提交" id="submit"/> </form> </body> </html>
Js代码 //将一个表单的数据返回成JSON对象 $.fn.serializeObject = function() { var o = {}; var a = this.serializeArray(); $.each(a, function() { if (o[this.name]) { if (!o[this.name].push) { o[this.name] = [ o[this.name] ]; } o[this.name].push(this.value || ‘‘); } else { o[this.name] = this.value || ‘‘; } }); return o; }; $(document).ready( function() { jQuery.ajax( { type : ‘GET‘, contentType : ‘application/json‘, url : ‘user/list‘, dataType : ‘json‘, success : function(data) { if (data && data.success == "true") { $(‘#info‘).html("共" + data.total + "条数据。<br/>"); $.each(data.data, function(i, item) { $(‘#info‘).append( "编号:" + item.id + ",姓名:" + item.username + ",年龄:" + item.age); }); } }, error : function() { alert("error") } }); $("#submit").click(function() { var jsonuserinfo = $.toJSON($(‘#form‘).serializeObject()); alert(jsonuserinfo); jQuery.ajax( { type : ‘POST‘, contentType : ‘application/json‘, url : ‘user/add‘, data : jsonuserinfo, dataType : ‘json‘, success : function(data) { alert("新增成功!"); }, error : function(data) { alert("error") } }); }); });
Java代码 @Controller @RequestMapping("/user") public class DemoController { private Logger logger = LoggerFactory.getLogger(DemoController.class); @RequestMapping(value = "/list", method = RequestMethod.GET) @ResponseBody public Map<String, Object> getUserList() { logger.info("列表"); List<UserModel> list = new ArrayList<UserModel>(); UserModel um = new UserModel(); um.setId("1"); um.setUsername("sss"); um.setAge(222); list.add(um); Map<String, Object> modelMap = new HashMap<String, Object>(3); modelMap.put("total", "1"); modelMap.put("data", list); modelMap.put("success", "true"); return modelMap; } @RequestMapping(value = "/add", method = RequestMethod.POST) @ResponseBody public Map<String, String> addUser(@RequestBody UserModel model) { logger.info("新增"); logger.info("捕获到前台传递过来的Model,名称为:" + model.getUsername()); Map<String, String> map = new HashMap<String, String>(1); map.put("success", "true"); return map; } }
时间: 2024-10-20 15:15:27