Ajax Programming practices

Source: Internet
Author: User
Tags ajax status code

---------------------------------------------------------------------------------------------------------------
[Copyright: The author of this article is original, reproduced please indicate the source]
Article Source: http://blog.csdn.net/sdksdk0/article/details/51727377
Juppé Id:sdksdk0
---------------------------------------------------------------------------------------------------------------

This article is mainly from the background of Ajax, to share what is Ajax? Why should we use AJAX? What is the application of Ajax? And how we're going to use Ajax. In this paper, Ajax's two common cases to explain the coding steps of Ajax, learning purposes require proficiency in AJAX 5 development steps. The prerequisite of learning has mastered the basic knowledge of html,css,js,xml,jsp,servlet.


First, Ajax introduction

Ajax, called "Asynchronous JavaScript and XML" (Asynchronous JavaScript and XML), is a web development technique that creates interactive Web applications.

Traditional web apps allow users to fill out forms (form) and send a request to the Web server when the form is submitted. The server receives and processes the form, and then returns a new page. This approach wastes a lot of bandwidth because most of the HTML code in the last two pages is often the same. Because each application interaction requires a request to the server, the response time of the application depends on the response time of the server. This causes the user interface to respond much more slowly than the local application.


Unlike this, an AJAX application can send and retrieve only the necessary data to the server, using SOAP or some other XML-based Web service interface, and using JavaScript on the client to process the response from the server. Because the amount of data exchanged between the server and the browser is much reduced, the result is that we can see applications that respond faster. At the same time, a lot of processing can be done on the client machine making the request, so the processing time of the Web server is also reduced.

Ajax works by adding an intermediate layer between the user and the server, which causes the user operation to be asynchronous with the server response. In this way, some of the previous workload of the server is passed on to the client, which is advantageous to the client's idle processing ability to deal with, reduce the burden of server and bandwidth, so as to save ISP's space and bandwidth leasing cost.




Second, Ajax usage scenarios


AJAX "fit" not to pass large amounts of data, but only to "pass a small amount of data", in the user's "experience", "more humane"

Ajax is a server-independent technology that servers can use: javaee,.net,php, ... These technologies are available

Ajax simply sends a request to the server, while receiving the server's HTML or XML or JSON carrier response

The server cannot use forwarding or redirection to a Web page, as this will cause a full refresh of the browser

That is, you can only respond to the browser in a streaming manner.


1, data validation: In text boxes and other input forms to give input prompts, or automatic completion, can effectively improve the user experience, especially those automatically completed data may come from the server side of the situation, Ajax is a good choice.


2, on-demand access to data:
Most of our previous processing of cascading menus was this:
In order to avoid overloading the page each time the operation of the menu, do not take each call to the background of the way, but once all the cascading menu of data read all and write to the array, and according to the user's operation with JavaScript to control its subset of the project rendering, although the operation of the response speed, The problem of not overloading the page and avoiding frequent requests to the server, but if the user does not manipulate the menu or only part of the menu, then part of the data that is read will become redundant data and waste the user's resources, especially when the menu structure is complex and the volume of data is large (such as the menu has many levels , each level and hundreds of items), this drawback is more prominent.
If Ajax is applied in this case, the result will be improved:
When the page is initialized, we only read all the data of its first level and show that, when one of the user Actions menu, it will request all data from the Level two submenu that the current level item belongs to by Ajax, and if you continue to request an item from the level two menu that has been rendered, Then ask for all the data for all level three menus that correspond to the two-level menu item you are manipulating, etc. In this way, with what to take what, how much to take as much, there will be no data redundancy and waste, reduce the total amount of data download, and update the page without overloading all content, only update the part that needs to be updated, compared to the background processing and overloading of the way to shorten the user wait time, but also the waste of resources to the lowest



Third, the AJAX Code 3.1 encoding step

1. Create an Ajax asynchronous object, for example: Createajax ()

2. Prepare to send asynchronous requests, for example: Ajax.open (Method,url)

3, if it is a POST request, be sure to set the AJAX request header, for example: Ajax.setrequestheader ()

If it is a GET request, you do not need to set the AJAX request header

4, really send the data in the request body to the server, for example: Ajax.send ()

5, Ajax constantly listening to the state of the server response changes, for example: Ajax.onreadystatechange, behind the write an unnamed processing function

6, in the nameless processing function, after obtaining the AJAX data, according to the DOM rule, uses the JS language to manipulate the Web page

3.2 Ajax Status Code

  • 0:ajax asynchronous object created, but not ready to send the request at the moment
  • 1:ajax has called the Open method, but has not actually sent the request yet
  • 2:ajax has called the Seng () method, but has not yet reached the server
  • 3: The request has reached the server, is processing, and the server is returning the response in the process
  • The 4:ajax asynchronous object has fully received the response information from the server, but this time the response status code is not necessarily correct, perhaps 404/500 or 200, etc.


  • 0-4 is the status code of the Ajax, each browser 0-3 of these 4 status display is different, but 4 this status code every browser has, so only need to know 4 on it.
  • It is important to have a state trigger before you can start function () {} functions, which do not trigger if the state remains 4-4-4.


Four, Ajax case one: automatic user name detection
here is mainly an input box, from the inside of the input content when the mouse jumps to the next input box, the right side will automatically detect the content. Here to register the user name detection as an example, here temporarily fixed the content written to the Sevlet file, you can choose to use JDBC to query the database of the user exists, here in order to more convenient demonstration of the role of Ajax, so the database is not used. Automatic detection can use the Get method and the Post method. This will be explained here.
4.1 Get mode

Here is an example of an automatic hint:

We can create a new Web project in MyEclipse and then write a registered JSP file, named register.jsp.

In this JSP in the HTML of the body to write the form first, and give its ID, the role here is mainly to give the following content through the getElementById element search.

<form >   user name: <input id= "Usernameid" type= "text"  name= "username"  maxlength= "ten"/> <span   id= "ResID" ></span>   </form>

Because some browsers may not support Ajax, we need to determine whether a browser is compatible. This means creating an Ajax object first.


function Createajax () {   var ajax=null;   try{   ajax=new ActiveXObject ("Microsoft.XMLHTTP");      } catch (E1) {   try{   ajax=new XMLHttpRequest ();   } catch (E2) {   alert ("Your browser does not support Ajax, please try changing your browser!") ");   }   }   return ajax;   }

then just follow the previously shared coding steps:

Positions the text box while providing the focus event   document.getElementById ("Usernameid"). Onblur=function () {   //Gets the value entered in the text box   var username =this.value.trim ();      If the content is empty if   (username.length==0) {   document.getElementById ("ResID"). Innerhtml= "User name cannot be empty";   } else{   //Utf-8 encoding   Username=encodeuri (username) for Chinese characters;   var ajax=createajax ();      var method= "GET";   var url= "${pagecontext.request.contextpath}/servlet/userservlet?time=" +new Date (). GetTime () + "&username=" + Username;   Ajax.open (Method,url);      Ajax.send (null);      Ajax.onreadystatechange=function () {   if (ajax.readystate==4) {   if (ajax.status==200) {   var tip= Ajax.responsetext;      document.getElementById ("ResID"). Innerhtml=tip;}}}}   

Here we need to use the servlet to do the server receive and verify the operation. This is done by the Get method.

public void doget (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException { String Username=request.getparameter ("username"); byte[] buf = username.getbytes ("iso-8859-1"); username = new String ( BUF, "UTF-8");//system.out.println (username); String tip= "<font color= ' green ' > Registered </font>"; equals (username)) {tip= "<font color= ' Red ' > The user already exists </font> ";} Response.setcontenttype ("Text/html;charset=utf-8"); PrintWriter pw=response.getwriter ();p w.write (Tip);p W.flush ();p w.close ();

run the Tomcat server. Accessed through the address.

The effect is as follows: When the mouse is removed, the user will be prompted to exist if there is one in the library.


If the user does not exist, it can be registered.


4.2 Post Mode

Many of the post methods are similar to the Get method, but there are still differences, such as the Post method needs to set the AJAX request header for post, which will automatically encode the requested Chinese characters utf-8. Here's an example of a picture tip:

Positions the text box while providing the focus event document.getElementById ("Usernameid"). Onblur=function () {//Gets the value entered in the text box var username=      This.value.trim ();   If the content is empty if (username.length==0) {document.getElementById ("ResID"). Innerhtml= "User name cannot be empty";      }else{var ajax=createajax ();   var method= "POST";   var url= "${pagecontext.request.contextpath}/servlet/userservlet?time=" +new Date (). GetTime ();      Ajax.open (Method,url); Set the AJAX request header to post, which will automatically encode the requested kanji Utf-8 ajax.setrequestheader ("Content-type", "application/x-www-form-urlencoded")      ;   var content= "Username=" +username;      Ajax.send (content);      Ajax.onreadystatechange=function () {if (ajax.readystate==4) {if (ajax.status==200) {var tip=ajax.responsetext; var imgelement = document.createelement ("img");//Set the Src/width/height property value of the img tag imgelement.src = tip; ImgElement.style.width = "15px"; imgElement.style.height = "15px";//Position span label var spanelement = document.getElementById ( "ResID");//Empty the contents of the span tag spanelement.innerhtml = "";//Add the IMG tag to the span tag SpanelemeNt.appendchild (imgelement); }   }      }      }   }
The 6th piece of the code is to parse the image that was read from the server and display it in span, which is the HTML page we set up earlier.

For Selvet, use the Post method:

public void DoPost (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException { Request.setcharacterencoding ("UTF-8"); String Username=request.getparameter ("username"); String tip= "Images/b.jpg", if ("Juppé". Equals (username)) {tip= "images/a.jpg";} Response.setcontenttype ("Text/html;charset=utf-8"); PrintWriter pw=response.getwriter ();p w.write (Tip);p W.flush ();p w.close ();

The effect is as follows:





V. Ajax case TWO: Provincial and municipal cascade

There are a lot of cases about the provinces and cities Cascade, where the client uses Ajax to get data from the server without flushing.

The first thing to do is to write the HTML file.

<select id= "Provinceid"  style= "width:120px" >    <option> Select Provinces </option>    <option> Hunan province </option>    <option> Guangdong </option>    </select>        <select  id= "Cityid" >    <option> Select City </option>     </select>
We also need to bring in the Createajax () that we wrote earlier.

<script  type= "Text/javascript"  src= "Js/ajax.js" ></script>

And then continue to write it in this script.


Locate the Province drop-down box while adding the content Change event document.getElementById ("Provinceid"). Onchange=function () {//empty var cityelement=document.get   Elementbyid ("Cityid"); cityelement.options.length=1;    Keep only the first//get the name of the selected province Var Index=this.selectedindex;    var optionelement=this[index];        Gets the contents of the selected option tag var province=optionelement.innerhtml;        if ("Select Province"!=province) {var ajax=createajax ();    var method= "POST";   var url= "${pagecontext.request.contextpath}/servlet/province?time=" +new Date (). GetTime ();      Ajax.open (Method,url); Set the AJAX request header to post, it will automatically utf-8 the requested weight of the man to encode Ajax.setrequestheader ("Content-type", "application/x-www-form-urlencoded      ");   var content= "province=" +province;      Ajax.send (content); Ajax.onreadystatechange=function () {if (ajax.readystate==4) {if (ajax.status==200) {var xmldocument=ajax.responsexml;   Follow the DOM to parse the XML document VAR cityelementarray=xmldocument.getelementsbytagname ("City");   var size=cityelementarray.length;   for (Var i=0;i<size;i++) {//innerhtml can only be used in html/jsp and cannot be used with Var city=cityelementarray[i].firstchild.nodevalue in XML;      var optionelement=document.createelement ("option");      optionelement.innerhtml=city;      Cityelement.appendchild (OptionElement); }      }   }      }      }        }


For the service side, the Post method is used:


public void DoPost (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException { Request.setcharacterencoding ("UTF-8"); String province=request.getparameter ("province"); Data response.setcontenttype in//xml format ("Text/xml;charset=utf-8"); PrintWriter pw = Response.getwriter ();p w.write ("<?xml version= ' 1.0 '  encoding= ' UTF-8 '?>");p W.write ("< Root> "), if (" Guangdong province ". Equals (province)) {pw.write (" <city> guangzhou </city> ");p w.write (" <city> Shenzhen </ City> ");p w.write (" <city> Foshan </city> ");} else if ("Hunan Province". Equals (province)) {Pw.write ("<city> Changsha </city>");p w.write ("<city> hengyang </city>") ;p w.write ("<city> Yongzhou </city>");p w.write ("<city> Zhuzhou </city>");} Pw.write ("</root>");p W.flush ();p w.close ();}


The effect is as follows:


Here is a no-refresh operation, can give the user a good interactive experience.




v. Summary
Ajax is an asynchronous refresh, and Ajax is a "local refresh" of "asynchronous" communication technology. Ajax is not a brand-new language, it is a new "programming model" introduced by Google in 2005, not the latest programming language. we need to master the use of XMLHttpRequest. Proficient in programming with Ajax.



Source Address: Https://github.com/sdksdk0/AJAX-Demo


Ajax Programming practices

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.