The JavaScript authoritative guide 20---xmlhttprequest and Ajax Solutions

Source: Internet
Author: User
Tags html form

I. Overview of AJAX

Ajax is an abbreviation for asynchronous JavaScript and XML. Chinese translation of asynchronous JavaScript and XML. AJAX is not a new programming language, but a new method of using existing standards. The art of exchanging data and updating parts of a Web page with the server without loading the page again.

At its core, theclient's JavaScript can be asynchronously exchanged with webserver.


Second, the AJAX foundation---XMLHttpRequest object

All modern browsers (ie7+, Firefox, Chrome, Safari, and Opera) are built-in XMLHttpRequest objects (IE5 and IE6 use ActiveXObject). XMLHttpRequest is used to exchange data with the server in the background. This means that you can update a part of a webpage without having to load the entire page again.


1. Create the syntax for the XMLHttpRequest object:

var obj1 = new XMLHttpRequest ();.

In IE5 and IE6. Use ActiveX object: var obj2 = new ActiveXObject ("Micorosoft.xmlhttp");

Be able to maintain compatibility in the following ways, for example:

var xmlhttp;if (window. XMLHttpRequest)  {//code for ie7+, Firefox, Chrome, Opera, Safari  xmlhttp=new XMLHttpRequest ();  } else  {//code for IE6, IE5  xmlhttp=new activexobject ("Microsoft.XMLHTTP");  }

2.XMLHttpRequestMethods and properties of the object

the methods and properties of the XMLHttpRequest object are used to send requests to the server and get the response from the server.

2.1 Sending requests: open () and send ()

The open () method is used to create a request. The HTTP request that was created was not sent until the call to the Send () method was sent

method does not distinguish between uppercase and lowercase. URLs can be absolute or relative addresses. Async feels true, meaning that it does not return data immediately. The string parameter is optional, which defines the body of the sending request (preferably in string format, and uses the setRequestHeader () method to define the content type and encoding of the request header).


2.2 setRequestHeader (): Sets the request header to be sent to the server with the request


Suppose you need to POST data like an HTML form, use setRequestHeader () to add an HTTP header. Then specify the data you want to send in the Send () method: Xmlhttp.open ("POST", "ajax_test.asp", True), Xmlhttp.setrequestheader ("Content-type", " Application/x-www-form-urlencoded "); Xmlhttp.send (" fname=bill&lname=gates ");

2.3 Abort (): Terminates the request. No number of references.


Third, Ajax get server response

Use XMLHttpRequest objects and properties to get the response of the server, including the HTTP header and the body of the response.

1, Xmlobj.getallresponseheaders (): Gets the header of the full response, returned as a string. Each HTTP header name and value is separated by a colon. such as Myheader:myvalue, and end with \ r \ n.


2, Xmlobj. getResponseHeader (param): Gets a specific field value in the response. The parameter param is the HTPP field name of a response.


3, ResponseText and Responsexml properties

Are read-only properties. Used to return the body of the response in the server.

<span style= "FONT-SIZE:14PX;" >//responsetext Property document.getElementById ("Mydiv"). Innerhtml=xmlhttp.responsetext;////responsexml Properties Xmldoc= Xmlhttp.responsexml;txt= ""; X=xmldoc.getelementsbytagname ("ARTIST"); for (i=0;i<x.length;i++)  {  txt= TXT + x[i].childnodes[0].nodevalue + "<br/>";  } document.getElementById ("mydiv") .innerhtml=txt;</span>


4. Status and StatusText attributes

are read-only properties that infer the response state.

Status indicates the state code in the response. such as 404,200, statustext represents the status text information. such as Ok,not Found. The status code and text information one by one correspond, common for example the following:


Click to view the full version.

These two properties are valid only after the Send () method sends the data and receives the server response complete.


5. ReadyState Properties

This property represents the status code of the HTTP request, read-only, and returns an integer with values and descriptions such as the following:

0 Description A state of "uninitialized"; at this point, a XMLHttpRequest object has been created, but it has not yet been initialized.
1 Descriptive narrative a "send" state; At this point, the code has called the XMLHttpRequest Open () method and XMLHttpRequest is ready to send a request to the server.
2 Descriptive narrative a "send" state; At this point, a request has been sent to the server side by means of the Send () method, but no response has been received.
3 Descriptive narrative a "receiving" state; at this point, the HTTP response header information has been received, but the message body part has not been fully received at the end.


4 Description A "loaded" state; At this point, the response has been fully received.


iv.onreadystatechange Events

The ReadyState attribute holds state information for XMLHttpRequest. Every time readyState changes. The onReadyStateChange event is triggered.

The onreadystatechange property can specify a function that is called when the state changes.

The function often determines the detailed state of the response with the Readystate/status/statustext property

Xmlhttp.onreadystatechange=function ()  {  if (xmlhttp.readystate==4 && xmlhttp.status==200)    {    document.getElementById ("mydiv"). Innerhtml=xmlhttp.responsetext;    }  }


V. Solve the problem of requests being cached by the browser

one of the issues to note when using XMLHttpRequest is that the contents of the load may be cached by the browser . Ability to make changes to URL parameters to avoid this problem.

The usual usage is to add a random number as a query parameter.

<span style= "color: #000000;" >xmlhttp.open ("GET", "demo_get.asp?t=" + math.random (), true); <span style= "Font-family:simsun;" >//or: Xmlhttp.open ("Get", "url" + (new Date ()). GetTime (), True);</span> xmlhttp.send ();</span>

Six, click to see the example

The JavaScript authoritative guide 20---xmlhttprequest and Ajax Solutions

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.