XMLHttpRequest object, xmlhttprequest

Source: Internet
Author: User

XMLHttpRequest object, xmlhttprequest

1. XMLHttpRequest object

(1) XMLHttpRequest is the object of the XMLHTTP component. With this object, AJAX can exchange data only with the server like a desktop application, instead of refreshing the interface every time, you do not need to hand over data processing to the server every time. This reduces the server load, speeds up response, and shortens user waiting time.

(2) XMLHttpRequest was first implemented in IE5 in the form of ActiveX components. Non-W3C standard.
Create an XMLHttpRequest object (inconsistent implementation methods due to non-standard features)
Internet Explorer implements XMLHttpRequest as an ActiveX Object
Other browsers (Firefox, Safari, Opera ...) Implement it as a local JavaScript Object.

XMLHttpRequest is compatible in different browsers, so you can access the attributes and methods of the XMLHttpRequest instance in the same way, regardless of the method created for this instance.

2. XMLHttpRequest object initialization

Function createXHR () {var xmlHttp; try {// Firefox, Opera 8.0 +, Safari xmlHttp = new XMLHttpRequest ();} catch (e) {// IE browser try {xmlHttp = new ActiveXObject ("Msxml2.XMLHTTP");} catch (e) {try {xmlHttp = new ActiveXObject ("Microsoft. XMLHTTP ");} catch (e) {alert (" your browser does not support AJAX! "); Return false ;}}}}
3. XMLHttpRequest object Method


4. XMLHttpRequest object attributes


5. onreadystatechange object attributes:
This event processing function is triggered by the server, not by the user.
During Ajax execution, the server notifies the client of the current communication status. This is implemented by updating the readyState of the XMLHttpRequest object. Changing the readyState attribute is a way for the server to connect to the client.
The readystatechange event is triggered every time the readyState attribute is changed.

XmlHttp. onreadystatechange = function () {// here we need to write some code}

6. readystate attributes:

Status Description
0 Request not initialized (before calling open)
1 Request Submitted (before sending () is called)
2 The request has been sent (here we can usually get the Content Header from the response)
3 Request Processing (some data is usually available in the response, but the server has not completed the response)
4 The request has been completed (you can access the server response and use it)
Understanding various states of drawing:


7. open (method, url, asynch) method
The open method of the XMLHttpRequest object allows programmers to send requests to the server using an Ajax call.
Method: Request type, which is a string similar to "GET" or "POST. If you only want to retrieve a file from the server without sending any data, use GET (you can send data in a GET request by appending the query string on the URL, however, the data size is limited to 2000 characters ). To send data to the server, use POST.
In some cases, Some browsers cache the results of multiple XMLHttpRequest requests in the same URL. If the response to each request is different, this will bring bad results. Append the current timestamp to the end of the URL to ensure the uniqueness of the URL, so that the browser does not cache the results.

Var url = "/FirstAjax/CityServlet? Time = "+ new Date (). getTime () +" & province = "+ province
Url: the path string pointing to the file on the server you requested. It can be an absolute or relative path.
Asynch: indicates whether the request needs to be asynchronously transmitted. The default value is true (asynchronous ). Specify true. You do not need to wait for the server to respond before reading the subsequent script. Specify false. When the script processing process passes through this point, it stops until the Ajax request is executed.

8. send (data) method:
The open method defines some details of Ajax requests. The send method can send commands for standby requests.
Data: The string to be passed to the server.
If a GET request is selected, no data is sent. If null is passed to the send method, request. send (null) is returned. If the value is passed, the server cannot receive it.
When providing parameters to the send () method, make sure that the method specified in open () is POST. If no data is sent as part of the Request body, use null.

9. setRequestHeader (header, value) method:

When a 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 GET or POST.
In an Ajax request, setRequestHeader can send the header information.
Parameter header: the name of the header; parameter value: the value of the header.
If a POST request is used to send data to the server, set the header of "Content-type" to "application/x-www-form-urlencoded ". it notifies the server that the data is being sent and the data is URL encoded.
This method can be called only after open ().
Complete Ajax POST request example:

// Prepare to send the request in POST Mode
Xhr. open ("post", "/FirstAjax/PostServlet? Time = "+ new Date (). getTime ());
// Set the request header. This request header is set only in POST mode.
Xhr. setRequestHeader ("content-type", "application/x-www-form-urlencoded ");
// Truly send the request
Xhr. send ("username =" + username );

10. Receiver method and attributes

The XMLHttpRequest method can be used to send requests to the server. During Ajax processing, the following attributes of XMLHttpRequest can be changed by the server:
ReadyState
Status
ResponseText
ResponseXML

(1). readyState

The readyState attribute indicates the current status of the Ajax request. Its value is represented by numbers ([0-4] values in the preceding table)

The readystatechange event is triggered every time the value of readyState is changed. If the onreadystatechange event handler is assigned to a function, every time the value of readyState changes, the function is executed.
Changes in the readyState value may vary depending on the browser. However, when the request ends, Each browser sets the value of readyState to 4.

(2) status
Each response sent by the server also carries the header information. The three-digit status code is the most important header in the response sent by the server and is part of Hypertext Transfer Protocol.
Common status codes and their meanings:
404 page not found (not found)
403 forbidden access (forbidden)
500 internal server error (internal service error)
200 everything is normal (OK)
304 not modified (not modified) (the server returns the 304 status, indicating that the source file is not modified)
In the XMLHttpRequest object, the status codes sent by the server are saved in the status attribute. By comparing the value with 200 or 304, you can ensure that the server has sent a successful response.

(3) responseText
The responseText attribute of XMLHttpRequest contains the data sent from the server. It is an HTML, XML, or plain text, depending on the content sent by the server. (Use the returned information as a string)
When the value of readyState is 4, The responseText attribute is available, indicating that the Ajax request has ended.

(4) responseXML (the returned information can be used as an XML document and can be processed by DOM .)
If the server returns XML, the data is stored in the responseXML attribute.
The responseXML attribute is available only when the server sends data with the correct header information. MIME type must be text/xml

11. AJAX development steps and details
(1x_create ajax_1.html or ajax_1.jsp
(2) Add events
(3) create an Ajax engine object after the event response
(4) Send requests Asynchronously
(5) Put the response results into the Ajax engine object
(6) Get Response Results from Ajax engine objects
(7) Use DOM and JS to dynamically add response results to Html or Jsp pages
(8) For POST requests, you must set the request header. The Code is as follows:
Xhr. setRequestHeader ("content-type", "application/x-www-form-urlencoded ");
After open (), before send ()
For GET requests, you do not need to set the Request Header


What is XMLHttpRequest?

1. What is an XMLHTTPRequest object?

The most common definition is: XmlHttp is a set of APIs that can be transmitted over http or receive XML and other data in scripting languages such as Javascript, VbScript, and Jscript. XmlHttp can be used to update part of the webpage without refreshing the entire page. (This function is one of the major characteristics of AJAX)

Explanation from MSDN: XmlHttp provides the protocol for communication between the client and the http server. The client can send a request to the http server through the XmlHttp object (MSXML2.XMLHTTP. 3.0) and use the Microsoft XML Document Object Model Microsoft? XML Document Object Model (DOM) processes the response.

Here are some external things. In fact, this thing has appeared very early, but in the past, the support of browsers was not enough, and only IE was supported. Therefore, most WEB programmers did not use it, but now the situation has changed a lot. Mozilla and Safari adopt it as the de facto standard, and mainstream browsers are beginning to support XMLHTTPRequest objects. However, it is important to note that XMLHTTPRequest is not yet a W3C standard, so it is slightly different in different browsers.

2. Create an XMLHTTPRequest object

Speaking of the difference, let's take a look at how to declare (use) it. Before using the XMLHTTPRequest object to send a request and process a response, we must use javascript to create an XMLHTTPRequest object. (IE implements XMLHTTPRequest as an ActiveX object, while other browsers [such as Firefox/Safari/Opear] implement it as a local javascript Object ). Next let's take a look at how to use javascript to create it:

The following is a reference clip:

<Script language = "javascript" type = "text/javascript">

<! --

Var xmlhttp;

// Create an XMLHTTPRequest object

Function createXMLHTTPRequest (){

If (window. ActiveXObject) {// determines whether ActiveX controls are supported

Xmlhttp = new ActiveObject ("Microsoft. XMLHTTP"); // create an XMLHTTPRequest object by instantiating a new instance of ActiveXObject

}

Else if (window. XMLHTTPRequest) {// determines whether to implement XMLHTTPRequest as a local javascript Object

Xmlhttp = new XMLHTTPRequest (); // create an instance of XMLHTTPRequest (local javascript Object)

}

}

// -->

</Script> 3. attributes and Methods

Since there are too many things, I will first use a page to list some methods and attributes. I will give you a detailed example later (I am also learning ).

<Html>

<Head>

<...... Remaining full text>

XmlHttpRequest object?

You are right.

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.