Core XMLHTTPRequest object of AJAX

Source: Internet
Author: User
XML in the browser

The XMLHTTPRequest object is the focus of AJAX (Asynchronous JavaScript + XML) Development examples, but it has not recently appeared. Microsoft first applied the XMLHTTPRequest object as an ActiveX Object in Windows ie5. Mozilla also applies a local compatible version of Mozilla 1.0 (with Netscape 7. Apple also applies this object in its Safari 1.2. The W3C DOM specification makes it a standard for network development.

The XMLHTTPRequest object allows JavaScript to send HTTP requests without reloading the page. In essence, HTTP requests are sent through the response received by the background. However, because there is no visible interruption, the user will continue to work without being aware of the background processing process. For developers, this is an unexpected result, resulting in a response to the user interface that can send data to the server in real time.

Method

The XMLHTTPRequest object contains a few methods, as shown below:

* Abort (): Terminate the current request.
* GetAllResponseHeaders (): returns a string containing the complete header label and value.
* GetResponseHeader ("name"): returns the string value of a specific header tag.
* Open ("method", "url", "Asynchronous flag", "username", and "password"): performs the installation function for the upcoming requests, you can specify optional parameters, user names, and passwords for URLs, methods (usually obtained or submitted), and asynchronous signatures.
* Sent (content): Send (established by the open method) requests. Optional content parameters may contain string or DOM format data.
* SetRequestHeader ("tag", "value"): allows you to specify the tag/value pair sent together with the request (created by the send method.

The third optional parameter of the open method is a Boolean value that controls whether you want to asynchronously process the upcoming transaction. This is where the asynchronous part of the Ajax initials enters the image. Asynchronous processing is the default side action (true), that is, after the send () method is called, the script is executed immediately without waiting for a response. If this value is set to false, the script waits for a request to be sent and the server returns the response before executing the script.

Attribute

The network or server may cause problems and cause the script to fail to be executed. Therefore, it is not always wise to wait for a response before processing. A more secure approach is to send and design code asynchronously when the onreadystatechange event of the request object occurs, as shown in the XMLHTTPRequest object Attribute Table below:

* Onreadystatechange: Event processor of the event caused by a change in each status.
* Readystate: the State of the object (0 = not initialized, 1 = loading, 2 = loading, 3 = interaction, 4 = completed ).
* Responsetext: The String Representation of the data returned by the server.
* Responsexml: DOM Representation of the data returned by the server.
* Status: the digital code of the HTTP status code requested by the server.
* Statustext: String information that is accompanied by the digit status code.

You can use the methods and attributes of the XMLHTTPRequest object to send requests in the background while the user continues to use the application software.

Understand objects in an application

There are two methods to apply the XMLHTTPRequest object in JavaScript code. The following is the IE Method:

Varreq = new activexobject ("Microsoft. XMLHTTP ");

The following is a non-ie method:

Varreq = new XMLHttpRequest ();

For this reason, based on your browser, you may want to include the code for creating an object instance, as shown in the following code:

If (window. XMLHttpRequest ){

Req = new XMLHttpRequest ();

} Else if (window. activexobject ){

Req = new activexobject ("Microsoft. XMLHTTP ");

}

In this way, a browser-based XMLHttpRequest class is created.

 

In list A, ASP. NET is used on the webpage to query the company name entered in the text box by phone number (I am using the standard SQL Server northwind database ). The javascript onblur event in the text field triggers the query.
List A <HTML> <Title> techrepublic.com example </title>
<SCRIPT type = "text/JavaScript" Language = "JavaScript">
Function gettelephone (cname ){
Document. Body. style. cursor = 'wait ';
Varobj = NULL;
If (window. XMLHttpRequest ){
OBJ = new XMLHttpRequest ();
} Else if (window. activexobject ){
OBJ = new activexobject ("Microsoft. XMLHTTP ");
}
Vargourl = "http: // localhost/test3.aspx? Cname = "+ cname
OBJ. Open ("Post", gourl, false );
OBJ. Send ();
If (obj. responsetext = "error") | (obj. responsetext = ""))
Alert ("the company name is invalid .");
Else
This.doc ument. Forms [0]. Telephone. value = obj. responsetext;
Document. Body. style. cursor = 'auto ';
}
</SCRIPT> <Form ID = "frmtext">
<Input type = "text" name = "telephone"/> <br/>
<Input type = "text" name = "cname" onblur = "gettelephone (this. Value);"/>
</Form>
</Body>

Tips for the HTML page:

* The gettelephone JavaScript method works with the XMLHTTPRequest object. It creates an object (based on the browser) and sticks the submitted value (from the text field) to the ASP. NET page.
* The returned value (responsetext attribute) of the XMLHTTPRequest object is used to determine whether data is not returned or an error is returned.
* The onblur event in the text field is associated with the JavaScript function. When a user clicks an out-of-domain event, the event is called.

In List B, the XMLHTTPRequest object calls ASP. NET code. ASP. NET page is very simple. It uses the value submitted to the page through the querystring variable to locate the matched data in the SQL Server database and return the matched data. If an exception occurs, an error is returned.

List B
<% @ Page Language = "C #" contenttype = "text/plain" DEBUG = "true" %>
<% @ Import namespace = "system. Data. sqlclient" %>
<% @ Import namespace = "system. Data" %>
<Script language = "C #" runat = "server">
Private sqlconnection conn = NULL;
Private sqlcommand cmd = NULL;
Private string connstring;
Private string strsql;
Private void page_load (Object sender, system. eventargs e ){
If (! Ispostback ){
Connstring = "Data Source = saleslaptop; uid = test; Pwd = test; initial catalog = northwind ";
Strsql = "Select phone from DBO. MERs where companyName like '%" + request. querystring ["cname"] + "% '";
Try {
Conn = new sqlconnection (connstring );
Cmd = new sqlcommand (strsql, Conn );
Conn. open ();
Response. Write (CMD. executescalar (). tostring ());
Conn. Close ();
} Catch (exception ex) {response. Write ("error ");
} Finally {
If (conn. State = connectionstate. Open ){
Conn. Close ();
} Conn. Dispose ();
}}}
</SCRIPT>

In this example, a terminal ASP. NET page is applied, but it can be used in any development language. In addition, because the terminal page simply applies the return value, the terminal page does not need to use the same development language or platform as the page that calls it. The terminal page may also be a network service.

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.