Use of Ajax in jquery (Java)

Source: Internet
Author: User

Ajax Way

JS: interface

var prjcontextpath= ' <%=request.getcontextpath ()%> ';
$ (document). Ready (function(){     //===============get==============================$ ("#username"). Blur (function() {$.ajax ({type:"GET", Url:prjcontextpath+ "/zhuceaction!queryusername.action?username=" + $ ("#username"). Val () + "&pwd=" +$ ("#pwd"). Val (), DataType:"JSON", Success:function(data) {if(data.success) {$ ("#usernamemsg"). HTML ("<font color= ' green ' >" + data.msg + "</font>"); } Else {                    $("#usernamemsg"). HTML ("<font color= ' Red ' >" + data.msg + "</font>"); }}, Error:function(JQXHR) {alert ("Error occurred:" +jqxhr.status);    }             });      }); //===============post==============================$ ("#username"). Blur (function() {$.ajax ({type:"POST", Url:prjcontextpath+ "/zhuceaction!queryusername.action", Data: {username: $ ("#username"). Val (), PWD: $ ("#pwd"). Val ()}, DataType:"JSON", Success:function(data) {if(data.success) {$ ("#usernamemsg"). HTML ("<font color= ' green ' >" + data.msg + "</font>"); } Else {                     $("#usernamemsg"). HTML ("<font color= ' Red ' >" + data.msg + "</font>"); }}, Error:function(JQXHR) {alert ("Error occurred:" +jqxhr.status);    }            }); });});

Call the method in the action:

Note: This action inherits Baseaction

 Public voidQueryusername ()throwsIOException {System.out.println ("Username=" +user.getusername ()); System.out.println ("Pwd=" +user.getpwd ()); //go to the database to verify        BooleanFlag =true; //form a JSON stringString html = ""; if(flag) {HTML= "{\" success\ ": 1,\" msg\ ": \" username, can be used! \"}"; } Else{html= "{\" success\ ": 0,\" msg\ ": \" username, not available! \"}"; }        //call a method in Baseaction to write a JSON string to the output streamResponsewriterjson (HTML); }
baseaction Code:
 PackageAction;Importjava.io.IOException;ImportJava.io.PrintWriter;ImportJavax.servlet.http.HttpServletResponse;ImportOrg.apache.struts2.ServletActionContext; Public classbaseaction { Publichttpservletresponse response; /*** Back to page data *@paramreturnstring Return Data *@throwsIOException Exception*/     Public voidResponsewriterjson (String returnstring)throwsIOException {Response=Servletactioncontext.getresponse (); Response.setcontenttype ("Application/json;charset=utf-8");            Response.getwriter (). write (returnstring);            Response.flushbuffer ();             Response.getwriter (). Close (); }    /*** Return page XML data *@paramreturnstring Return Data *@throwsIOException Exception*/     Public voidResponsewriterxml (String returnstring)throwsIOException {Response=Servletactioncontext.getresponse (); Response.setcharacterencoding ("Utf-8"); Response.setcontenttype ("Text/xml"); Response.setheader ("Cache-control", "No-cache");            Response.getwriter (). write (returnstring);            Response.flushbuffer ();            Response.getwriter (). Close (); }    /*** Back to page data *@paramreturnstring *@throwsIOException Exception*/     Public voidPrintWriter (String returnstring)throwsIOException {Response=Servletactioncontext.getresponse (); Response.setcontenttype ("Text/html;charset=utf-8"); PrintWriter out=Response.getwriter ();            Out.println (returnstring);            Out.close (); }    }

Post mode

Js:

//-----------Query the user name start-------------------------------------------$ (document). Ready (function() {query (); });//-----------Query the user name end-------------------------------------------//Load query Land registration approval form (judge: Add/update/search)functionquery () {varUsername = "AA"; varPWD = "BB"; $.post (Prjcontextpath+ "/updateaction!query.action", {username:username,pwd:pwd},callbackquerysuccess);}functioncallbackquerysuccess (JSON) {if(Json.data! =NULL|| Json.data! = "")    {        //Assigning a value to a page        /** Method 1 for (Var i=0;i<json.data.length;i++) {var tbbody = "";            var trcolor= "";            Alert ("i=" +i);                        var editdata=json.data[i];            if (i% 2 = = 0) {Trcolor = "even";            } else {trcolor = "odd"; } Tbbody + = "<tr class=" + trcolor + "><td>" + editdata.name + "</td>" + "<td>" + EDI            Tdata.age + "</td></tr>";        $ ("#myTb"). Append (Tbbody); }        */                        //Assigning a value to a page Method 2         varTypedata =Json.data; $.each (Typedata,function(i, n) {varTbbody = ""varTrcolor; if(i% 2 = = 0) {Trcolor= "even"; }            Else{Trcolor= "Odd"; } tbbody+ = "<tr class=" + trcolor + "><td>" + n.name + "</td>" + "<td>" + n.age + "</td>" + "<t D> "+ n.like[0" + "</td></tr>"; $("#myTb"). Append (Tbbody);            }); }}

Action

 PackageAction;Importjava.io.IOException;Importjava.util.ArrayList;Importjava.util.List;ImportBean. User;ImportBean. UserInfo;ImportCom.alibaba.fastjson.JSON;ImportCom.opensymphony.xwork2.ModelDriven; Public classUpdateactionextendsBaseactionImplementsModeldriven<user>{User User=NewUser ();  PublicUser Getmodel () {returnuser; }     Public voidQuery ()throwsIOException {System.out.println ("Username=" +user.getusername ()); System.out.println ("Pwd=" +user.getpwd ()); UserInfo UserInfo=NewUserInfo (); Userinfo.setname ("Zhang San"); Userinfo.setage (20); Userinfo.setbirthday ("1990-10-09"); String[] Likes=NewString[] {"Basketball", "football" };        Userinfo.setlike (likes); Userinfo.sethasgirlfirend (false); Userinfo.setcar (NULL); UserInfo Userinfo2=NewUserInfo (); Userinfo2.setname ("John Doe"); Userinfo2.setage (20); Userinfo2.setbirthday ("1991-11-11"); String[] Likes1=NewString[] {"Billiards", "Badminton" };        Userinfo2.setlike (LIKES1); Userinfo2.sethasgirlfirend (false); Userinfo2.setcar (NULL); List<UserInfo> userjsonlist =NewArraylist<userinfo>();        Userjsonlist.add (userinfo);        Userjsonlist.add (Userinfo2); String Jsonarray=json.tojsonstring (userjsonlist); StringBuffer responsestring=NewStringBuffer (); Responsestring.append ("{\" total\ ":"). Append (2). Append (", \" data\ ":"). Append (Jsonarray). Append ("}");        System.out.println (Responsestring.tostring ()); //call a method in Baseaction to write a JSON string to the output streamResponsewriterjson (responsestring.tostring ()); /**{"Total": 2, "data": [{"Age": "Birthday": "1990-10-09", "Hasgirlfirend": false , "like": ["basketball", "football"], "name": "31"}, {"Age": "Birthday": "1990-10-09", "have Girlfirend ": false," like ": [" basketball "," soccer "]," name ":" Zhang San "}]}*/        }}

Use of Ajax in jquery (Java)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.