Simple Ajax call implemented by jquery + JSON
Userservlet. Java code
Package COM. ISS. servlet; import Org. JSON. jsonexception; import Org. JSON. jsonobject; import COM. ISS. pojo. user; import COM. ISS. util. jsonutil; public class userservlet extends httpservlet {public void doget (httpservletrequest request, httpservletresponse response) throws servletexception, ioexception {dopost (request, response);} public void dopost (httpservletrequest, httpservletresponse response) throws servletexception, ioexception {response. setcontenttype ("text/html; charset = UTF-8"); // List add Object List <user> userlist = new arraylist <user> (); user user1 = new user ("Zhang San", "male", "18"); User user2 = new user ("Li Si", "male", "19 "); user user3 = new user ("Wang Wu", "male", "20"); userlist. add (user1); userlist. add (user2); userlist. add (user3); printwriter out = response. getwriter (); string STR = NULL; try {// returns the list to the interface if (request. getparameter ("username "). equals ("jquery") & request. getparameter ("password "). equals ("ajax") {STR = jsonobject. quote (jsonutil. tojsonstring (userlist);} Out. print (STR);} catch (jsonexception e) {// todo auto-generated Catch Block E. printstacktrace ();} system. out. println ("str" + Str); out. flush (); out. close ();}}
HTML code
<Body> account jquery password Ajax <Form ID = "mainform"> <ul> <li> account <input type = "text" name = "username"/> </LI> <li> password <input type = "password" name = "password"/> </LI> <li> <input onclick = "login () "type =" button "value =" login "/> </LI> </ul> </form> the queried data <Div id =" Diva "> </Div> <SCRIPT type = "text/JavaScript"> function login () {// obtain the form parameter var ARGs =$ ("# mainform "). serialize (); // call jquery JSON to obtain the method // the three parameters are: Find the path, request parameters, and return the data callback function $. getjson ("Servlet/userservlet", argS, function (data) {If (Data! = NULL) {// The interface returns a JSON String called JSON. parse () converts data to JSON // format object var jsondata = JSON. parse (data); parsedata (jsondata);} else {alert ("incorrect account and password entered") ;}} function parsedata (data) {var STR = ""; // traverse JSON format data for (var key in data) {strstr = STR + "user" + data [Key]. username + "Age" + data [Key]. age + "<br/>" alert (STR);} // Add data to Div $ ("# diva" ).html (STR );} </SCRIPT> </body>
Userservlet remember to import tool class jsonstringobject jsonutil
JSP imports jquery. js and JSON. js