Talking about Ajax

Source: Internet
Author: User

Talking about Ajax

The core technology of Ajax is javascript,xmlhttprequest,dom.

XMLHttpRequest, the main communication agent, realizes the asynchronous data interaction between client and server side;

DOM, dynamically update the loaded pages for dynamic display and interaction;

JavaScript, which writes the scripting language of the Ajax engine, is responsible for binding and processing all the data.

XML, the format of data interaction, with the popularity of XML, it will become an indispensable part of Ajax.

First, the advantages of Ajax are:

1. No Refresh update page, take data on demand, update only the parts that need to be updated, do not need to refresh the entire page, reduce the burden on the server

2. Further promote the separation of page rendering and data, especially the use of XML data representation.

Second, using Ajax

The XMLHttpRequest object is the key technology to implement AJAX application, which is responsible for the asynchronous interaction between Ajax and server, so the application of Ajax is carried out around the creation, sending request and processing response of XMLHttpRequest object.

1, create the XMLHttpRequest object

Function Createxmlhttp () {

Var request;

Var browser=navigator.appname;//Gets the name of the browser used by the user

Using IE, the XMLHTTP object is created using MSXML.

If (browser== "Microsoft Internet Explorer") {

Var arrversions=["msxml2.xmlhttp.5.0", "msxml2.xmlhttp.4.0", "msxml2.xmlhttp.3.0", "MSXML2." XMLHttp "," Microsoft.XMLHTTP "];

for (Var i=0;i<arrversions.length;i++) {

try{

Find a supported version and wear a XMLHTTP object from there

Request=new ActiveXObject (Arrversions[i]);

return request;

}

Catch (Exception) {

Ignore

}

}

}

If it's a Mozilla browser

else{

Returns a XMLHttpRequest object

Request=new XMLHttpRequest ();

return request;

}

}

So far we've created a XMLHttpRequest object that spans IE and Mozilla browsers.

The following uses the XMLHttpRequest object we obtained to send the request to the server

2. Send a request to the server

Using the above created function common XMLHTTP object instance, send the request to the corresponding server, can be a GET request, or it can be a POST request. The following is an example of a GET request that sends a request to the server. The code is as follows:

Function send_request (URL) {

Creating an XMLHTTP Object instance

var http_req=createxmlhttp ();

The Open function establishes a connection, which must be an asynchronous way

Http_req.open ("GET", url,true);

Declaring a callback function

Http_req.onreadystatechange=processrequest;

Send Request

Http_req.send (NULL);

}

3. Handling Server Response

In the callback function declared in the previous step, receive the data returned by the server and dynamically update the page as needed (usually with DOM assistance) or do some other action (such as pop-up warnings, etc.), the simple code is as follows:

Function ProcessRequest () {

4 indicates the request is complete

If (http_req.readystate==4) {

200 is the correct request

If (http_req.status==200) {

Gets the response text for the server

Var Responsestr=http_req.responsetext;

Processing the returned data, this is just the way the data is displayed as a warning box

alert (RESPONSESTR);

}

else{

Alert ("Request page exception");

}

}

}

}

Second, the application scenario

1, data validation

Traditional Web applications, the entire form will be sent to the server for verification, so that the verification time is longer and unnecessary burden on the server, while the user filling in an item can not be timely access to information. Using AJAX, you can asynchronously send the item form data to the server for validation of the data when the user fills in the form, and immediately return to the processing result, without having to refresh the entire page and update only one part of the page dynamically.

The specific code is implemented as follows: register.jsp

<script>

Function Createxmlhttp () {

Var request;

Var browser=navigator.appname;//Gets the name of the browser used by the user

Using IE, the XMLHTTP object is created using MSXML.

If (browser== "Microsoft Internet Explorer") {

Var arrversions=["msxml2.xmlhttp.5.0", "msxml2.xmlhttp.4.0", "msxml2.xmlhttp.3.0", "MSXML2." XMLHttp "," Microsoft.XMLHTTP "];

for (Var i=0;i<arrversions.length;i++) {

try{

Find a supported version and wear a XMLHTTP object from there

Request=new ActiveXObject (Arrversions[i]);

return request;

}

Catch (Exception) {

Ignore

}

}

}

If it's a Mozilla browser

else{

Returns a XMLHttpRequest object

Request=new XMLHttpRequest ();

return request;

}

}

Creating a XMLHTTP Object instance variable

var http= createxmlhttp ();

Send Request

function Chkuser () {

Request "Checkusername" Servlet

Var url= "Checkusername";

Var Name=document.getelementbyid ("UserName"). Value;

url+= ("? username=" +escape (name) + "&oprate=chkuser");

Http.open ("GET", url,true);

http. Onreadystatechange=processresponse;

Send Request

Http.send (NULL);

Return

}

Handling the response of the server

Function ProcessResponse () {

4 indicates the request is complete

If (http.readystate==4) {

200 is the correct request

If (http.status==200) {

Gets the response text for the server

Var Responsestr=http.responsetext;

if (responsestr== "The user is valid, you can use") {

document.getElementById ("Showstr"). Innertext=http.responsetext;

}

else{

Alert ("Not available");

}

}

}

}

</script>

<body>

<center>

<form action= "/control?act=register" >//form form requested Control.java, accompanied by a parameter passed to the class act

<input type= "text" name= "UserName" onblur= "Chkuser ()" >

<div id= "Showstr" ></div>

<input type= "Submit" >

</form>

</body>

Target page register.jsp request "Checkusername", The latter is a server-side servlet program (Checkusername.java), which we simply process, where a list of strings is declared to hold the user name that has been used, and the GET request response function obtains the requested user name parameter, determines whether it already exists and returns the result to the client. The Checkusername.java source code for the server is as follows:

public class Checkusername extends httpservlet{

Private String msgstr= "";

Public string[] Usernamelist;

Responding to GET request functions

Protected void doget (HttpServletRequest request, httpservletresponse response) {

String oprate= (String) request.getparameter ("Oprate");

String Username= (String) request.getparameter ("username");

try{

If (Oprate.equals ("Chkuser")) {

Boolean flag=this. Iscontain (username);//Look at the database has the wood has this function

If (! Flag) Response.getwriter (). Writer ("The user name is valid and can be used!"). ”)

}

}}}

Protected void DoPost (HttpServletRequest request, httpservletresponse response) {

Doget (Request,response);

}

The initialization function of the servlet

public void init (ServletConfig config) {

Usernamelist=new string[]{"Tom", "Jack"};

}

Private Boolean iscontain (String param) {

for (int i=0;i<usernamelist.length;i++) {

If (Usernamelist[i].equals (param)) {

Return true;

}

Else continue;

}

Return false;

}

}

2. Cascading directory Instances

JavaScript adds the Opction method to select three ways:

  1. <script type="Text/javascript" >
  2. function Add () {
  3. var testselect = document.getElementById ("Testselect");
  4. //alert (testSelect.options.length);
  5. //Mode 1
  6. var op=document.createelement ("option");
  7. Op.appendchild (document.createTextNode ("Way One"));
  8. //Mode 2
  9. Testselect.appendchild (OP);
  10. Testselect.options[testselect.options.length] = new Option ("Way Two", "way Two");
  11. //Mode 3
  12. var OP1 = New Option ("Way Three","way Three",true,true);
  13. TestSelect.options.add (OP1);
  14. }
  15. </script>
  16. <body>
  17. <select name="Testselect" id="Testselect" >
  18. <option label="test1" value="test1" >123</option>
  19. </select>
  20. <input type="button" value="Add" onclick="Add ()"/>
  21. </body>

Talking about 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.