Ajax instance (. NET)

Source: Internet
Author: User
Document directory
  • 5.2 Ajax basic http://book.csdn.net/bookfiles/653/10065320712.shtml
  • 5.2.1 XMLHTTPRequest object

 

5.2 Ajax basic http://book.csdn.net/bookfiles/653/10065320712.shtml

Before Ajax development, we must first understand some basic knowledge. Although Ajax. net has encapsulated Ajax Implementation Details and greatly simplified our operations. However, understanding the basic Ajax implementation method helps us better understand and implement it in development, and more effective optimization and troubleshooting are crucial. In addition, although we do not have to write a specific Ajax call proxy, we can get the data before calling the proxy and how to display the data correctly after the data is returned, both work requires the ability to operate the DOM model with basic JavaScript. Next we
In the future, we will discuss these aspects.

5.2.1 XMLHTTPRequest object

For the basis and core of Ajax technology, the XMLHTTPRequest object should be an object we must understand. The key to Ajax implementation is to send asynchronous requests and receive response execution callbacks. XMLHttpRequest was first introduced in Microsoft Internet Explorer 5.0 as an ActiveX component. Later, various browser vendors implemented the XMLHTTPRequest object by using JavaScript built-in objects. Although
Its implementation methods are different, but most browsers provide similar properties and methods, which are slightly different in actual scripting methods and achieve the same effect, at present, W3C is committed to setting a unified standard for XMLHttpRequest objects so that various browser vendors can comply with them to facilitate the promotion and development of Ajax technology.

XMLHttpRequest provides a relatively simple and easy-to-use API, next we will briefly introduce the attributes and methods it provides and how to use these attributes and methods to process Ajax requests and responses.

1. readystate attributes

When an XMLHTTPRequest object is created, this attribute identifies the status of the object. We can access this attribute, to determine the status of the request and then perform corresponding operations. The meanings of the specific value of this attribute are shown in Table 5-1.

Table 5-1

Value

Description

0

The status is not initialized. At this time, an XMLHTTPRequest object has been created, but the attributes of this object have not been initialized.

1

Prepare the sending status. At this time, you have called the open () method of the XMLHTTPRequest object and are ready to send an XMLHttpRequest request to the server.

2

The status has been sent. At this time, the send () method of the XMLHTTPRequest object has been called, but no response has been received.

3

Receiving status. At this time, the httpresponse response information has been received but the receiving has not been completed.

4

The response status is completed. At this time, the httpresponse response is received.

2. responsetext attributes

This attribute describes all the text content in httpresponse. By accessing it, you can get all the text content returned by the response in XMLHttpRequest. This attribute has partial or full values only when the value of readystate is 3 or 4. Otherwise, this attribute will only be a null string.

3. responsexml attributes

Only when the readystate attribute is 4 and the Content-Type MIME type in the response header is specified as XML (text/XML or application/XML, this attribute is parsed as an XML document. Otherwise, this attribute is null. If the XML document to be returned has a poor structure or has not finished returning the response, this attribute is also null. Therefore, this attribute is used to describe the XML document attributes parsed by XMLHttpRequest.

4. Status attributes

It is used to describe the status value of the server's HTTP request. With this attribute value, we can determine the server's response status. For example, we usually determine whether the server returns normally by determining status = 200. However, note that this attribute can be accessed only when the daily readystate is 3 or 4.

5. Status attributes

This attribute is used to describe the status Text of the server HTTP request. You can obtain the description text of the server response status, which is the same as the status attribute, this attribute can be accessed only when readystate is 3 or 4.

6. onreadystatechange event

This event is triggered whenever the readystate changes. This event is usually used to trigger a callback handler.

7. open () method

The XMLHTTPRequest object is initialized using the open (method, Uri, async, username, password) method. By calling this method, you can get a send () method. The method parameter is used to specify the httprequest type for sending requests. The value type is string, and the value can be get, post, put, delete, etc; the URI parameter is used to specify the address of the server to which the request is sent. This address is automatically parsed as an absolute address, so the relative address can be used here;
Async is a parameter of the boolean type. It is true by default. This parameter indicates asynchronous submission. If you want to send a synchronous request, set this parameter to false; when the server needs to verify the access to the user, we can set the username and password parameters.

When the open () method is called, the XMLHTTPRequest object sets the readystate attribute to 1 and initializes other attributes. If a request is being sent or the response is being received, the data and content of the previous request will be lost and the request will be canceled.

8. Send () method

After the open () method is called, we can call the send () method to send the request according to the parameters set in the open () method. When the async parameter in the open () method is true, return immediately after the send () method is called. Otherwise, the request will be interrupted until it is returned. Note that the send () method must be called after the open () method is called when the readystate is 1. After the send () method is called and the response header is received, the value of readystate is set to 2. Once the response message is received,
The value of readystate is set to 3 until the response is received.

9. Abort () method

This method can suspend sending of an httprequest request or receiving httpresponse, and set the XMLHTTPRequest object to the initialization status.

10. setRequestHeader () method

This method is used to set the httprequest header information after the open () method is called. the setRequestHeader (header, value) method contains two parameters. The first one is the header key name, the latter is its value.

11. getResponseHeader () method

When readystate is 3 or 4, this method is used to obtain the header information of httpresponse. In addition, we can also get the header information of all httpresponse through getAllResponseHeaders.

After figuring out the basic attribute methods of XMLHttpRequest, we can start to write our first Ajax program. We are going to click a button and use ajax to retrieve a hello World from the server! Is displayed in a text box.

Create a page named ajaxtest. aspx in a configured site project. First, write the following code in the page_load event function of the CS file:

Ajaxtest. aspx. CS:

Protected void page_load (Object sender, eventargs E)

{

If (request. querystring ["S"] = "1") // use a query string to indicate that the request is sent through Ajax.

{

Response. Write ("Hello world! "); // Output Hello world to httpresponse!

Response. End (); // sends the page buffer to the client browser and terminates the page output.

// If this sentence is removed, Additional HTML code will be obtained.

}

}

Relatively speaking, we will write more code on the front-end page. Slowly, you will find that this may be a practice of Ajax:

Ajaxtest. aspx:

<% @ Page Language = "C #" autoeventwireup = "true" codefile = "ajaxtest. aspx. cs" inherits = "ajaxtest" %>

<! Doctype HTML public "-// W3C // dtd xhtml 1.0 transitional // en" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<HTML xmlns = "http://www.w3.org/1999/xhtml">

<Head runat = "server">

<Title> test </title>

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

<! --

Function getinfo () {// we use this function to obtain information asynchronously.

VaR xmlhttpreq = NULL; // declare an empty object to load XMLHttpRequest

If (window. XMLHttpRequest) {// in a browser other than ie5 IE6, XMLHttpRequest is a sub-object of window.

Xmlhttpreq = new XMLHttpRequest (); // we use this method to instantiate an XMLHttpRequest

}

Else if (window. activexobject) {// ie5 IE6 introduces the XMLHttpRequest

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

// Ie5 IE6 adopts this method

}

If (xmlhttpreq! = NULL) {// if the object is instantiated successfully, we can work.

Xmlhttpreq. Open ("get", "ajaxtest. aspx? S = 1 ", true );

// Call the open () method and use the Asynchronous Method

Xmlhttpreq. onreadystatechange = requestcallback; // sets the callback function.

Xmlhttpreq. Send (null); // you can call it using the null parameter because the get method is used for submission.

}

Function requestcallback () {// this function will be called once the value of readystate changes

If (xmlhttpreq. readystate = 4)

{

Document. getelementbyid ("ipttext"). value = xmlhttpreq. responsetext;

// Assign the value of xmlhttpreq. responsetext to the ipttext Control

}

}

}

-->

</SCRIPT>

</Head>

<Body>

<Form ID = "form1" runat = "server">

<Div>

<Input id = "ipttext" type = "text" value = "/>

<Input type = "button" id = "" value = "ajax submit" onclick = "getinfo ();"/>

<! -- Click this button to call -->

</Div>

</Form>

</Body>

</Html>

If you find "Hello World!" in the text box lightning as you click the button !", Congratulations! You have completed an Ajax call. If you still don't understand the code on the front-end page that seems to be isolated from C #, it doesn't matter. Next, let's take a look at another important part of Ajax-JavaScript.

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.