Application of Java Ajax

Source: Internet
Author: User

I. Steps to use AJAX

Step One: create an AJAX asynchronous object , for example: Createajax ()

Step Two: prepare to send asynchronous requests , for example:ajax.open (Method,url)

Step Three: if it is POST Request , be sure to set the AJAX request header, for example:Ajax. setRequestHeader ()

if it is GET request without setting the AJAX request header

Step four: actually send the data in the request body to the server, for example:ajax.send ()

Step Five: AJAX constantly listens for changes in the state of the service-side response , such as:Ajax.onreadystatechange, followed by an unnamed handler

Step Six: In the Nameless handler function, Get AJAX Data , follow the DOM rules, use the JS language to manipulate Web pages

Two. Use instances (toggle state) When we click on the image to switch to another state, and the picture changes

1. When we click on the image will go to the servlet's Doget method

public void doget (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException {// Gets the browser-side data string Lid=request.getparameter ("lid");  String isshow=request.getparameter ("Isshow"); Linkservice  service=new Linkserviceimpl (); int FLAG=1;//1 indicates success 0 indicates failure try{//execute modify isshow value Service.updateisshow ( Integer.parseint (lid), Integer.parseint (Isshow));} catch (Exception e) {flag=0;} Return to Browser//response.setcontenttype ("text/html"); PrintWriter out = Response.getwriter (), if (flag==1) out.print ("1"), Elseout.print ("0"); Out.close ();}

2. Call the service layer's modification method

public void updateisshow (int lid,int isshow) {String sql = "UPDATE Link SET    isshow=?   " WHERE  lid=? "; Connection conn = Jdbcutil.getconn (); PreparedStatement PS = null;try {PS = conn.preparestatement (sql);p s.setint (1, isshow==1?0:1);p s.setint (2, lid); Ps.execute ();} catch (SQLException e) {e.printstacktrace ();} Jdbcutil.closeall (NULL, PS, conn);}

3. Go to the page to invoke the method in Ajax and pass in the ID and current state isshow

 <script type= "Text/javascript" &GT;//1 get Ajax built-in object function Createajax () {var Ajax = null;try {ajax = new ActiveXObject (" Microsoft.XMLHTTP ");} catch (e) {ajax = new XMLHttpRequest ();} return Ajax;}  var obajax = Createajax (), var info = "", var vlid = "", function changeisshow (lid, isshow) {vlid = lid;if (isshow = = 1) {Info = "Do not display    ";} Else{info = "Show    ";} 2 Prepare to send asynchronous request method request Get,post, request address Urlvar URL = "linkchangeservlet?lid=" + lid + "&isshow=" + isshow+ "&date S= "+new Date (); Obajax.open (" Get ", url),//4 sends data in the request body obajax.send (null);//5 listening Status Obajax.onreadystatechange = function () {//a server is receiving data correctly readyState ==4 if (obajax.readystate = = 4) {//b Server correctly returns data to browser status==200if (Obajax.status = = 200) {//receive the data returned by the server, Reponsetext returnAll text information in changecity.jsp in Out.println () var riceive = obajax.responsetext;if (riceive = = 1) {document.getElementById (" Isshowinfo "+ vlid). InnerHTML = info;} else {alert (' modification failed ');}}};} </script>//jquery among the Ajax<script src= ". /js/jquery.js "></script><script>function changeisshowtwo (lid, isshow) {if (isshow = = 1) {info =" does not display    ";} Else{info = "Show    ";} Call jquery in Ajax for Get way var url = "Linkchangeservlet?lid=" + lid + "&isshow=" + isshow+ "&dates=" +new Date (); $.get ( Url,null,function (data) {if (data==1) {$ ("#isshowInfo" +lid). HTML (info);}  Else{alert (' failure ');});   }</script><c:foreach items= "${pagemodel.list}" var= "link" varstatus= "vs" >

4. Assigning values

<div id= "Isshowinfo${link.lid}" >   ${link.isshow==0? " Do not show ":" Display "}    </div>

  

The original state such as

The state after the change, such as

Summarize:

XMLHttpRequest ( i.e.:AJAX) objects Common events, methods, and properties

(1) event:

Ajax.onreadystatechange: Indicates that the AJAX Asynchronous object constantly listens to the server's response,

is triggered by the server program, not by the programmer

(2) Properties:

Ajax.readystate==0: Indicates that the AJAX Asynchronous object has been created, but has not yet called the Open () method

Ajax.readystate==1: Indicates that the AJAX Asynchronous object has called the Open () method, but has not yet called send () Method

ajax.readystate==2: Indicates that the AJAX Asynchronous object has called the Send () method, but the request has not yet reached the server side

Ajax.readystate==3: Indicates that the server has received a request for an AJAX Asynchronous object that is processing the response ...

ajax.readystate=="4": Indicates that the AJAX Asynchronous object has completely received the server's response information, but the received data is not necessarily correct /c12>

None of the above 5 states are the same for all browsers, but the status 4 is the same for each browser

ajax.status==200: Indicates that the AJAX Asynchronous object received a response code, if it is a number , indicating that everything is OK

Ajax.responsetext: Represents the acquisition of data from an AJAX Asynchronous Object in an HTML Vector

Ajax.responsexml: Represents the acquisition of data from an AJAX Asynchronous object in an XML vector

(3) method:

Ajax.open (Method,url, optional boolean value )

AJAX asynchronous objects prepare to send asynchronous requests

parameter one: In what way to send, commonly used GET or POST, case insensitive

parameter two: Send to where to go, commonly used Servlet or Struts2 or SPRINGMVC to receive,

This is limited to Java EE disciplines

parameter three: The default value is true, which means that AJAX objects are submitted "asynchronously" to the server

if set to false, the AJAX object is submitted to the server in a "synchronous" manner

Ajax.setrequestheader ("Content-type", "application/x-www-form-urlencoded")

represents the content in the request body, as UTF-8 is encoded in a way that is valid only for POST requests

Ajax.send (content)

AJAX Asynchronous objects really send asynchronous requests

parameter one: indicates content in the HTTP "request Body"

if it is GET mode:content = null, if force is passed to the server, the service end is not received, return null

if it is POST mode:content! = null, for example:username=jack&password=123&role=admin

Application of Java Ajax

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.