Ajax Series II: core object XMLHttpRquest

Source: Internet
Author: User

The previous article introduced the basic knowledge of ajax. This article uses a simple example of user verification to explain it to you!

First, you can understand this object: the XMLHttpRequest object can be used to update webpages without submitting the entire page to the server. After all the pages are loaded, the client requests data from the server through this object. After the server receives and processes the data, it reports the data to the client. The XMLHttpRequest object provides full access to the HTTP protocol, including the ability to make POST and HEAD requests and common GET requests. XMLHttpRequest can synchronously or asynchronously return the response of the Web server and return the content in the form of text or a DOM document. Although the name is XMLHttpRequest, it is not limited to use with XML documents: it can receive any form of text documents.

XMLHttpRequest is well supported by all modern browsers. The unique browser dependency involves creating an XMLHttpRequest object. In IE 5 and IE 6, ActiveXObject () constructors specific to IE must be used.

Let's take a look at this small example below:

Front-end code:

<% @ Page Language = "C #" AutoEventWireup = "true" CodeBehind = "verifyUserName. aspx. cs" Inherits = "VerifyUserName. verifyUserName" %>    
     <Script src = ".. /common. js "> </script> <script type =" text/javascript "> var xmlhttp; function submit () {// obtain the value var username = document. getElementById ("username "). value; if (username = "" | username = null) {lele.info (username); alert ("Enter the data to be verified! "); Return;} var xmlhttp; if (window. XMLHttpRequest) {// create an XMLHttpRequest object instance xmlhttp = new XMLHttpRequest (); // applicable to ie7, ie8, firefox browser // fix bugs in some specific versions of javasillar browsers if (xmlhttp. overrideMimeType) {xmlhttp. overrideMimeType ("text/xml");} // all browsers can pass this verification! Put it below to improve performance} else if (window. activeXObject) {// ie5, ie6, ie7, ie8, firefox, etc. var activexName = ["MSXML2.XMLHTTP. 6.0 "," MSXML2.XMLHTTP. 5.0 "," MSXML2.XMLHTTP. 4.0 "," MSXML2.XMLHTTP. 3.0 "," MSXML2.XMLHTTP "," Microsoft. XMLHTTP "]; for (var I = 0; I <activexName. length; I ++) {try {xmlhttp = new ActiveXObject (activexName [I]); break;} catch (e) {}}// if creation fails, the browser does not support xmlHttpRequest if (xmlhttp = Undefined | xmlhttp = null) {alert ("This browser does not support xmlHttpRequest"); return ;} // register the callback function of this object (the data returned by the background !) Note: Only the function name is required. Do not enclose xmlhttp in parentheses. onreadystatechange = callback; // GET method // xmlhttp. open ("GET", "yz. ashx = "+ username, true); // send data // xmlhttp. send (null); // sets the xmlhttp parameter for interaction with the server. open ("POST", "yz. ashx ", true); // indicates that the encoding method for the content submitted by the client to the server text is URL encoding, that is, except for standard characters, each byte is represented by "%" before the double-byte hexadecimal notation. // Of course, there are other encoding methods, such as CONTENT-TYPE: multipart/form-data. xmlhttp. setRequestHeader ("Content-Type", "application/x-www-form-urlencoded"); // post Submit data! Xmlhttp. send ("username =" + username); // callback function. process the returned data in this function! Function callback () {// determines whether the interaction is successful if (xmlhttp. readyState = 4 & xmlhttp. status = 200) {// accept the data returned by the server var message = xmlhttp. responseText; var div = document. getElementById ("message"); div. innerHTML = message; alert (message) ;};}</script>                                        

Background code:

Public class yz: IHttpHandler {public void ProcessRequest (HttpContext context) {context. response. contentType = "text/plain"; context. response. charset = "charset = gb2312"; // specify the encoding format // obtain the parameter value string oldString = context. request. params ["username"]. toString (); // string oldString = context. request. queryString ["username"]. toString (); if (oldString = "") {context. response. write ("the user name cannot be blank! "); Return;} if (oldString =" Zhang Hongjie ") {context. response. write ("the user name already exists");} else {context. response. write ("the user name does not exist and can be used ");}}

Verification Result

Through the above example, we can see that xmlHttpRequest is used according to the steps!

Step 5 of using this object:

1. Create this object

2. Registration callback Method

3. set parameters for interaction with the server using the open method

4. Set the server side to send data, and enable interaction with the server side to send data

5. Determine whether the interaction between the server side is complete and whether the server side correctly puts back the data


Is there any knowledge about the usage of the XmlHttpRequest object. But if we want to have a better understanding of this object, we also need to understand other attributes and methods of this object.

Attribute:

ReadyState

HTTP Request status. When an XMLHttpRequest is created for the first time, the value of this attribute starts from 0 until the complete HTTP response is received. This value is increased to 4. Each of the five States has an associated informal name. The following table lists the status, name, and meaning:

Status

Name

Description

0

Uninitialized

Initialization status. The XMLHttpRequest object has been created or reset by the abort () method.

1

Open

The open () method has been called, but the send () method has not been called. The request has not been sent.

2

Send

The Send () method has been called and the HTTP request has been sent to the Web server. No response is received.

3

Processing ing

All Response Headers have been received. The response body starts receiving but is not completed.

4

Loaded

The HTTP response has been fully received.

The value of readyState will not decrease unless a request calls the abort () or open () method during processing. The onreadystatechange event handle is triggered every time the value of this attribute is increased.

ResponseText

The response body received from the server (excluding the header) So far, or if no data is received, it is a null string.

If readyState is less than 3, this attribute is an empty string. When readyState is 3, this attribute returns the response that has been received. If readyState is 4, this attribute stores the complete response body.

If the response contains a header that specifies the character encoding for the response body, this encoding is used. Otherwise, it is assumed that the Unicode UTF-8 is used.

ResponseXML

The response to the request is parsed as XML and returned as a Document object. If the response body is not "text/xml", null is returned.

Status

The HTTP status code returned by the server. For example, 200 indicates success, and 404 indicates "NotFound" error. When readyState is less than 3, reading this attribute will cause an exception.

StatusText

This attribute specifies the HTTP status code of the request by name rather than number. That is to say, when the status is 200, it is "OK", and when the status is 404, it is "NotFound ". Like the status attribute, when readyState is less than 3, reading this attribute causes an exception.

Method:

Abort ()

Cancels the current response, closes the connection, and ends any pending network activities. This method resets the XMLHttpRequest object to the readyState to 0 and cancels all pending network activities. For example, if the request takes too long and the response is no longer necessary, you can call this method.

GetAllResponseHeaders ()

Return the HTTP Response Header as an unparsed string. If readyState is less than 3, this method returns null. Otherwise, it returns the headers of all HTTP responses sent by the server. The header is returned as a single string, with one header in one row. Each line is separated by a linefeed.

GetResponseHeader ()

Returns the value of the specified HTTP response header. The parameter is the name of the HTTP response header to be returned. You can use any case to specify the header name, which is case insensitive to the response header. The return value of this method is the value of the specified HTTP Response Header. If this header is not received or the readyState is less than 3, it is a null string. If multiple headers with a specified name are received, the value of this header is connected and returned. The values of each header are separated by commas (,) and spaces.

Open ()

Initialize HTTP request parameters, such as URLs and HTTP methods, but do not send requests.

Send ()

Send an HTTP request, use the parameters passed to the open () method, and the optional request body passed to the method.

SetRequestHeader ()

Set or add an HTTP request to an opened but not sent request.


Through the above explanation, can you use the xmlHttpRequest object for interaction? Try Asynchronous interaction and enjoy it.

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.