(1) Simple interaction:
<table style= "width: 100%" class= "table" cellspacing= "1" cellpadding= "1" Border= "0" > <tr><td class= "ti1" colspan= "2" > Please select the interrogation room </td> </tr> <tr><td class= "Ti2hui" > Interrogation room name </td><td class= "TI1CU" > <select id= "Roomid" name= "Roomid" > <c:foreach items= "${roomlist}" var= "Hostel" > < 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=" OK "/> </td></tr></table>
------------------------------the parameters submitted by the AJAX-----can be submitted through a URL, or can be submitted in data:{}-------------------------------
Function setshow () { $.ajax ( { type : "POST", url : "<%=request.getcontextpath ()%>/initroom.do? Method=set ", data : { '" &NBSP;: $ ("#roomid"). Find (' option:selected '). Text (), ' Roomid ' :$ ("# Roomid "). Val () }, dataType: " JSON ", success : function (data) { if (data.success) { alert ("Setup succeeded! "); } else{ alert ("Setup failed! "); } }, error :function () { alert ("Network connection Error! "); } }); }
------------------------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 ("the"); Session.setattribute ("Roomid", Roomid); Session.setattribute ("Roomname", "Guest"); SYSTEM.OUT.PRINTLN ("Session Set:" +room+ "= =" +roomid); Response.setcharacterencoding ("Utf-8"); Response.getwriter (). Write ("{\" success\ ": true}"); Response.getwriter (). Flush (); }
(2) Springmvc return information to Ajax:
Import Com.googlecode.jsonplugin.JSONUtil; list<records> recordlist = new arraylist<records> ();//Get recordlist operation omit Response.setcharacterencoding (" Utf-8 "); Response.getwriter (). Write ("{\" success\ ": true, \" Data\ ":" + jsonutil.serialize (recordlist) + "}"); Response.getwriter (). Flush ();
-------------------------------Ajax to process serialized objects--------------------------------------------
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) state-of-the-art practices:
In Spring MVC3, it is convenient to respond and accept JSON.
Using the annotation @responsebody, you can convert the results (a map containing strings and JavaBean) to JSON.
Using @RequestBody annotations The foreground only needs to submit a conforming json,spring to the Controller that will automatically assemble it into a bean.
Spring this transformation is implemented by the Org.codehaus.jackson component, all of which require the introduction of JACKSON-CORE-ASL and Org.codehaus.jackson two jar packages
HTML code <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> JS code //returns data from a form into a JSON object $.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 ( &Nbsp; function () { jquery.ajax ( { type : ' GET ', contentType : ' Application/json ', url : ' User/list ', dataType : ' json ', success : function (data) { if (data && data.success == "true") { $ (' #info '). HTML ("Total" + data.total + "bar data. <br/> "); $.each ( Data.data, function (i, iTEM) { $ (' #info '). Append ( "No.:" + item.id + ", Name:" + item.username + ", Age:" + 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 ("added success! "); }, error : function (data) { alert ("error") } }); }); });
Java code @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"); 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 ("new"); Logger.info ("Capture to the foreground passed the model, the name is:" + model.getusername ()); map <String, String> map = new HashMap<String, String> (1); map.Put ("Success", "true"); return map; } }
Ajax interacting with spring MVC