What is Ajax? Detailed use of Ajax (full instance included)

Source: Internet
Author: User

This article mainly introduces the definition of Ajax, as well as the specific use of Ajax, now let's read this article

1. What is Ajax?

A technique that allows a browser to communicate with a server without having to refresh the current page, called Ajax. In the actual programming process, often xmlhttprequest as a synonym for Ajax, XMLHttpRequest is an extension of JavaScript.

2.XMLHttpRequest

2.1 Creating the Xmlhttpreques object:

var request = new Xmlhttpreques ();

Common methods and properties for 2.2XMLHttpReques objects:


2.3 Programming using the JavaScript language

<! DOCTYPE html>

Using the XMLHttpRequest instance to communicate with the server contains 3 key:

①onreadystatechange event handler function:

--| The event handler is triggered by the server, not the user;

--| during Ajax execution, the server notifies the client of the current state of communication. This is accomplished by updating the readyState of the XMLHttpRequest object. Changing the ReadyState property is a way for the server to connect to the client. The ReadyStateChange event is triggered every time the ReadyState property is changed

②open (method, URL, asynch):

--| The Open method of the XMLHttpRequest object allows the programmer to send a request to the server with an Ajax call.

--|method: The request type , a string similar to "GET" or "POST". If you want to retrieve only one file from the server without sending any data, use get (you can send the data in a GET request by appending the query string to the URL, but the data size is limited to 2000 characters). If you need to send data to the server, use POST.

--| in some cases, some browsers cache the results of multiple XMLHttpRequest requests at the same URL. If the response to each request is different, it will result in bad results. when you append the timestamp to the end of the URL, you can ensure that the URL is unique, thus avoiding the browser caching the results.

--|url: The path string that points to the file on the server you requested. Can be either an absolute path or a relative path.

--|asynch: Indicates whether the request is to be transmitted asynchronously, and the default value is true. Specifies true to not wait for the server to be appropriate before reading the following script. Specifies false, when the script process passes this point, to stop until the AJAX request is completed before proceeding (want to see more on the Topic.alibabacloud.comAJAX Development manual)

③send (data):

The--|open method defines some details of the Ajax request. The Send method can send instructions for a request that is already on standby

--|data: The string that will be passed to the server.

--| If a GET request is selected, no data is sent and null is passed to the Send method: Request.send (NULL);

--| when supplying parameters to the Send () method, ensure that the method specified in open () is post, and null is used if no data is sent as part of the request body.

④setrequestheader (Header,value):

--| when the browser requests a page from the server, it sends a set of header information along with the request. The header information is a series of metadata that describes the request (metadata). The header information is used to declare whether a request is a GET or POST.

--| In an Ajax request, the job of sending the header information can be done by setRequestHeader

--| parameter header: The name of the header; The value of the parameter value: header.

--| If you send data to the server with a POST request, you need to set the header of "Content-type" to "application/x-www-form-urlencoded". It tells the server that the data is being sent, And the data already conforms to the URL encoding.

--| the method must be open () before calling the

⑤readystate

The--|readystate property represents the current state of the AJAX request . Its value is represented by a number.

-----I represents uninitialized. The Open method has not been called

-----| \ Rep is loading. The open method has been called, but the Send method has not yet been called

The----the proxy has been loaded. Send has been called. The request has started

----|3 represents the interaction. The server is sending a response

----|4 representative completed. Response sent complete

--| each time the ReadyState value changes, the ReadyStateChange event is triggered . If the onReadyStateChange event handler is assigned to a function, then each change in the ReadyState value causes the function to execute.

Changes in the--|readystate values vary depending on the browser. However, when the request is finished, each browser will set the value of the readyState to 4 uniformly

⑥status

Each response sent by the--| server also comes with a header message. The three-digit status code is the most important header information in the response sent by the server and is part of the Hypertext Transfer Protocol.

--| commonly used status codes and their meanings:

----|404 not found page (not found)

----|403 Forbidden (Forbidden)

----|500 Internal Server error (internal service error)

----|200 all normal (OK)

----|304 has not been modified (not modified)

--| In the XMLHttpRequest object, the status codes sent by the server are saved in the status attribute. By comparing this value to 200 or 304, you can ensure that the server has sent a successful response

⑦responsetext

--| The ResponseText property of XMLHttpRequest contains the data sent from the server. It is a html,xml or plain text, depending on what the server sends.

--| when the ReadyState property value becomes 4 o'clock, the ResponseText property is available, indicating that the AJAX request has ended.

⑧responsexml

--| If the server returns XML, the data will be stored in the Responsexml attribute.

--| the Responsexml property is available only when the server sends data with the correct header information. The MIME type must be Text/xml

3.Ajax data Format (HTML XML JSON)

3.1 HTML

(1) HTML is made up of some ordinary text. If the server sends HTML through XMLHttpRequest, the text is stored in the ResponseText property.

(2) You do not have to read the data from the ResponseText property. It is already in the desired format and can be inserted directly into the page.

(3) The simplest way to insert HTML code is to update the InnerHTML property of this element.

Window.onload = function () {var anodes = document.getElementsByTagName ("a"); for (var i = 0;i < anodes.length;i++) { Anodes[i].onclick = function () {var request = new XMLHttpRequest (); var method = "GET"; var url = this.href;request.open (meth Od,url); request.send (null); request.onreadystatechange = function () {if (request.readystate = = 4) {if (Request.status = = 200 | | Request.status = = 304) {document.getElementById ("Details"). InnerHTML = Request.responsetext;}}} return false;}}

3.2 XML

Advantages:
(1) XML is a common data format.
(2) Instead of forcing data into a defined format, you need to customize the appropriate markup for the data.
(3) The DOM gives you complete control over the document.
Disadvantages:
(1) If the document comes from the server, you must ensure that the document contains the correct header information. If the document type is incorrect, then the value of Responsexml will be empty.
(2) DOM parsing can be complicated when a long XML file is received by the browser

Window.onload = function () {var anodes = document.getElementsByTagName ("a"); for (var i = 0;i < anodes.length;i++) { Anodes[i].onclick = function () {var request = new XMLHttpRequest (); var method = "GET"; var url = this.href;request.open (meth Od,url); request.send (null); request.onreadystatechange = function () {if (request.readystate = = 4) {if (Request.status = = 200 | | Request.status = = 304) {//1 gets XML file contents var result = request.responsexml;/* * Parse XML file: 

3.3 JSON

(1) JSON (JavaScript Object Notation) is a simple data format that is lighter than XML. JSON is a native JavaScript format, which means that working with JSON data in JavaScript does not require any special APIs or toolkits.
(2) The JSON rule is simple: an object is an unordered collection of "name/value pairs". An object starts with "{" (opening parenthesis) and "}" (the closing parenthesis) ends. Each "name" is followed by a ":" (colon); "' Name/value ' pair ' is separated by", "(comma).

Window.onload = function () {var anodes = document.getElementsByTagName ("a"); for (var i = 0;i < anodes.length;i++) { Anodes[i].onclick = function () {var request = new XMLHttpRequest (); var method = "GET"; var url = this.href;request.open (meth Od,url); request.send (null); request.onreadystatechange = function () {if (request.readystate = = 4) {if (Request.status = = 200 | | Request.status = = 304) {var jsonstr = Request.responsetext;var Jsonobject = eval ("(" + Jsonstr + ")"); var name = Jsonobject . Person.name;var Website = Jsonobject.person.website;var email = Jsonobject.person.email;var Anode = Document.createelement ("a"); Anode.appendchild (document.createTextNode (name)); anode.href = "mailto:" + Email;var H2node = document.createelement ("H2"); H2node.appendchild (anode); var aNode1 = Document.createelement ("a"); Anode1.appendchild (document.createTextNode (website)); anode1.href = Website;var Detailsnode = document.getElementById ("Details");d etailsnode.innerhtml = "";d etailsnode.appendchild (h2node);d Etailsnode.aPpendchild (ANODE1);}}} return false;}}}

4. Using jquery to implement AJAX technology

jquery encapsulates Ajax operations, $.ajax () at the bottom of jquery, the second layer is load (), $.get () and $.post (), and the third layer is $.getscript () and $.GETJSO N ().

4.1 Load () method

$ (function () {$ ("a"). Click (function () {var url = This.href;var args = {"Time": New Date ()};$ ("#details"). Load (URL); return false;})

(1) The load () method is the simplest and most commonly used Ajax method in JQuery, which can load remote HTML code and insert it into the DOM. Its structure is: Load (url[, Data][,callback]), where url:string type, request htm The URL address of the page; data (optional): Object type, Key/value data sent to the server, callback (optional): function type, callback function when the request completes, whether the request succeeds or fails.

(2) If you only need to load certain elements within the target HTML page, you can use the URL parameter of the load () method to achieve the purpose. By specifying the selector with the URL parameter, it is convenient to select the desired content from the loaded HTML document. The URL parameter of the load () method has a syntax structure of "URL selector" (Note: There is a space between the URL and the selector)

$ (function () {$ ("a"). Click (function () {///Select return H2 descendants in HTML results page a element var url = this.href + "H2 a"; var args = {"Time": New Date ()}; $ ("#details"). Load (URL); return false;})

(3) Delivery mode: the Load () method of the transfer parameters according to the parameter data from the dynamic custom. If no parameter is passed, it is passed by GET method, otherwise POST is used

(4) For operations that must be loaded before they can continue, the load () method provides a callback function that has three parameters: the data representing the requested return content; Textstatus object and XMLHttpRequest object representing the request state

4.2$.get () or $.post () method

4.2.1 Loading XML data

$ (function () {$ ("a"). Click (function () {var url = This.href;args = {"Time": New Date ()};$.get (url,args,function (data) { var name = $ (data). Find ("name"). Text (), var email = $ (data). Find ("email"). Text (), var website = $ (data). Find ("website"). Text (); $ ("#details"). Empty ()             . Append ("

4.2.2 Loading HTML data

$ (function () {$ ("a"). Click (function () {var url = This.href;var args = {"Time": New Date ()};$.get (url,args,function (data) {$ ("#details"). empty (); $ (data). AppendTo ($ ("#details"));}); return false;})

4.2.3 Loading JSON data

$ (function () {$ ("a"). Click (function () {var url = This.href;args = {"Time": New Date ()};$.get (url,args,function (data) { var name = Data.person.name;var Email = Data.person.email;var Website = data.person.website;$ ("#details"). Empty ()             . Append ("

This is the end of this article (want to see more on the Topic.alibabacloud.comAJAX User manual section of the study), there are questions can be in the message below the question.

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.