Core Ajax objects-Quick Start With XMLHttpRequest

Source: Internet
Author: User
Tags response code
Introduction:

For non-tgb instances, skip this step ......

After jquery started school, the computer stopped for a while. When I got bored one day, I took my BS stuff and looked at it again. I found many familiar and unfamiliar things in it.

Most of the content in the course of learning the Ajax of Mr. Wang xingkui was previously learned. When I was learning about JS, I had a lot of JS materials. Many people look at Niu Yu JS and Jiang Hao's Js. But my master asked me to see Li Yanhui's Js. It was strange at the beginning. One week for niujia's Js and one week for Jiang Hao's Js. Li Yanhui's Js 150 set is said to be at least three weeks.

Although I feel a little stressed. However, the content of these 150 sets is quite useful only when it is actually viewed. The previous sections explain the basics. A project later explains how jquery is encapsulated from Js. And Ajax entry-level technologies.

When I was reading Ajax, I found that basically everything was learned. Now let's take a look at the basics of Ajax. View an instance.

 

Ajax basics:

 

I have been talking about it for a long time, and now I am entering the topic.

 

What Is Ajax?

Ajax Abbreviation: asynchronousjavascript and XML, that is, asynchronous JS and XML.

Ajax allows the client to not refresh data when requesting data from the server.

 

It is the interaction between the client and the server, which can be performed continuously.

That is, requests sent by the client do not affect the use of the client.

 

What is the difference between synchronization and Asynchronization?

Synchronization:

The client requests a piece of data from the server, and the page is reloaded (refreshed ).

Asynchronous:

Client request data. The page is directly obtained without refresh.

 

Ajax technology can make web pages more friendly. The whole page will not be refreshed because a small part of content is operated.

The core technology of AJAX is the XMLHTTPRequest object (xhr ). The role of this object is equivalent to the delegate of the client.

 

Traditional page design:

When you request data, you must wait for the server to return the data before proceeding to the next step. (This may cause no response)

 

Ajax webpage:

After the client sends the request data, it can still be used. (Do not refresh the page) for example, Baidu's search box. Does not stop responding because you have entered the content.

 

XMLHTTPRequest object, used as the "secretary" of the client to interact with the server.

 

Comparison between traditional web pages and Ajax web pages

 

Getting started with Ajax: Learn XMLHttpRequest in five steps

HTML page:

 

<! Doctype HTML> <! -- To change this license header, Choose License headers in project properties. to change this template file, choose tools | templatesand open the template in the editor. --> <HTML> 


The following is a five-step process:

1. Create an XMLHTTPRequest object

// 1. create the XMLHTTPRequest object if (window. XMLHttpRequest) {// IE7, IE8, Firefox, mozillar, Safari, opera // alert ("IE7, IE8, Firefox, mozillar, Safari, opera "); XMLHTTP = new XMLHttpRequest (); If (XMLHTTP. overridemimetype) {XMLHTTP. overridemimetype ("text/XML") ;}} else if (window. activexobject) {// IE6, ie5.5, ie5 var activename = ["msxml2.xmlhttp. 6.0 "," msxml2.xmlhttp. 5.0 "," msxml2.xmlhttp. 4.0 "," msxml2.xmlhttp. 3.0 "," msxml2.xmlhttp "," miscrosoft. XMLHTTP "]; for (VAR I = 0; I <activename. length; I ++) {try {XMLHTTP = new activexobject (activename [I]); break;} catch (E) {}}} if (XMLHTTP = undefined | XMLHTTP = NULL) {alert ("the current browser does not support creating XMLHttpRequest objects. Please change the browser"); return ;}

2. register the callback function

// 2. register the callback method XMLHTTP. onreadystatechange = callback;

Note: When registering a callback function, you only need to assign a value to the function name. If callback () is assigned, the value is the result of function execution.

3. set parameters for interaction with the server

// 3. Set the parameter (get) var username = Document. getelementbyid ("username"). value; XMLHTTP. Open ("get", "Ajax? Name = "+ username, true); // true indicates asynchronous mode // 3. set the corresponding parameter (post) for interaction with the server // XMLHTTP. open ("Post", "ajax", true); // XMLHTTP. setRequestHeader ("Content-Type", "application/X-WWW-form-urlencoded ");

4. send data to the server

// 4. Set the data sent to the server and start interaction with the server. XMLHTTP. Send (null );

 

5. Determine whether the interaction with the server is complete and whether data is returned.

// 5. determine whether the interaction on the server is complete, and whether the server returns data if (XMLHTTP. readystate = 4) {// indicates that the interaction with the server has completed if (XMLHTTP. status = 200) {// indicates that the server's response code is 200, and the data is returned correctly. // The method for accepting data in plain text var message = XMLHTTP. responsetext; // The Acceptance Method of the DOM object corresponding to the XML data // The premise is that the server needs to set Content-Type to text/XML // var domxml = XMLHTTP. responsexml var messagenode = document. getelementbyid ("message"); messagenode. innerhtml = message ;}}

NOTE: If it is difficult to understand, you can study the attributes and events of the XMLHTTPRequest object.


If there is only the above HTML, the running result must be faulty ...... No Web server is running. Who does the HTML client interact?

 

In this case, you should create a web server. Create a servlet using the Tomcat server

/** To change this license header, Choose License headers in project properties. * To change this template file, choose tools | templates * and open the template in the editor. */import Java. io. ioexception; import Java. io. printwriter; import javax. servlet. servletexception; import javax. servlet. HTTP. httpservlet; import javax. servlet. HTTP. httpservletrequest; import javax. servlet. HTTP. httpservletresponse; /***** @ author Zhao Chong */public class Ajax extends httpservlet {/*** processes requests for both HTTP <code> Get </code> and <code> post </code> * methods. ** @ Param request Servlet Request * @ Param response servlet response * @ throws servletexception if a servlet-specific error occurs * @ throws ioexception if an I/O error occurs */protected void processrequest (httpservletrequest request, httpservletresponse response) throws servletexception, ioexception {response. setcontenttype ("text/html; charset = UTF-8"); try (printwriter out = response. getwriter () {/* todo output your page here. you may use following sample code. */string old = request. getparameter ("name"); If (old = NULL) {out. println ("user name cannot be blank");} else {string name = new string (old. getbytes ("ISO8859-1"), "gb2312"); system. out. println (name); If (name. equals ("zhaochong") {out. println ("username [" + name + "] already exists. Please use another username");} else {out. println ("username [" + name + "] does not exist. Please use another username ");}}}}


When creating a servlet, you only need to modify the content in the processrequest function. When creating a servlet, please automatically generate xml

 

The above demo is performed on netbean IDE. Although this is a small example, I found that many of them do not understand ...... For example, the difference between Tomcat and glashfish and the meaning of the content in XML files. When watching the video, you can see that the development environment configuration is ignored.

 

Summary

Through the above example, we can first understand the differences between Ajax and traditional pages. For a deeper understanding, you must repeat it multiple times and apply it in the project to be proficient.


 

 

 

Core Ajax objects-Quick Start With XMLHttpRequest

Related Article

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.