Ajax learning diary (1)

Source: Internet
Author: User

1. Create an instance of the XMLHTTPRequest object
If the browser supports ActiveX objects, you can use ActiveX to create XMLHttpRequest objects. Otherwise, it is necessary to use the local JavaScript Object technology to create.
VaR XMLHTTP;
Function createxmlhttprequest (){
If (window. activexobject ){
XMLHTTP = new activexobject ("Microsoft. XMLHTTP ");
}
Else if (window. XMLHttpRequest ){
XMLHTTP = new XMLHttpRequest ();
}
}

Some methods of XMLHttpRequest object:
A. Void open (string method, string URL, Boolean asynch, string username, string password ):
This method creates a call to the server. This is a pure script method for initializing a request. It has two required parameters and three optional parameters. Provides specific methods (get, post, put), and URLs of resources called. In addition, a Boolean value can be passed to indicate whether the call is asynchronous or synchronous. The default value is true, indicating that the request is asynchronous in nature. If this parameter is set to false, the processing will wait until the slave server returns a response. Asynchronous calling is the main advantage of Ajax. The last two parameters allow you to specify a specific user name and password.
B. Void send (content ):
This method sends a request to the server. If the request is declared asynchronous, this method will return immediately, otherwise it will wait until the response is received. Optional parameters can be DOM object instances, input streams, or strings. The content passed in this method will be used as part of the Request body.
C. Void setRequestHeader (string header, string value ):
This method sets the value for a given header in an HTTP request. It has two parameters. The first string indicates the header to be set, and the second string indicates the value to be placed in the header. It must be noted that this method can be called only after open () is called.

Open () and send () are the most likely to be used in all these methods ().
D. Void abord (): stops the request.
E, string getAllResponseHeaders ():
This method returns a string containing all the Response Headers of the HTTP request, including Content-Length, data, and URL.
F, string getResponseHeader (string header ):
This method corresponds to getAllResponseHeaders (), but it has a parameter that indicates the specified header value you want to obtain and returns the value as a string.

Attributes of the XMLHTTPRequest object:
Onreadystatechange: This event processor is triggered for every state change. A JavaScript function is usually called.
Readystate: The Request status. Five values are available: 0 = not initialized, 1 = loading, 2 = loaded, 3 = interaction, and 4 = completed.
Responsetext: server response, which is a string.
Responsexml: Server Response, expressed as XML, which can be parsed as a DOM object.
Status: the HTTP status code of the server (200 corresponds to OK, 404 corresponds to not found, and so on ).
Statuetext: the text of the HTTP status code (OK or not found ).

Standard Ajax request response methods:
A. A client triggers an Ajax event. From a simple onchange event to a specific user action, many such events can trigger Ajax events.
<Input type = "text" id = "email" name = "email" onblue = "validateemail ()";>
B. Create an instance of the XMLHTTPRequest object. Use the open () method to create a call, and set the URL and the expected HTTP method (usually get or post). The request is actually triggered by a send () method call.
VaR XMLHTTP;
Function validateemail (){
VaR email = Document. getelementbyid ("email ");
VaR url = "validate? Email = "+ escape (email. value );
If (window. activexobject ){
XMLHTTP = new activexobject ("Microsoft. XMLHTTP ");
}
Else if (window. XMLHttpRequest ){
XMLHTTP = new XMLHttpRequest ();
}
XMLHTTP. Open ("get", URL );
XMLHTTP. onreadystatechange = callback;
XMLHTTP. Send (null );
}
C. make a request to the server. May call servlet, CGI script, or Task Server technology.
D. The server can do what you want, including accessing the database or even accessing another system.
E. The request is returned to the browser. Content-Type is set to text/XML -- XMLHTTPRequest object can only process results of the text/html type. In other more complex examples, the response may be more extensive, including JavaScript, Dom management, and other related technologies. Note that you need to set other headers so that the browser does not cache the results locally. The following code can be used:
Response. setheader ("cache-control", "No-Cache ");
Response. setheader ("Pragma", "No-Cache ");
F. In this example, the XMLHTTPRequest object is configured to call the callback () function when processing the returned result. This function checks the readystate attribute of the XMLHTTPRequest object and then checks the status code returned by the server. If everything is normal, the callback () function will do some interesting work on the client.
Function callback (){
If (XMLHTTP. readystate = 4 ){
If (XMLHTTP. Status = 200 ){
// Do something interesting here
}
}
}

2. Send simple requests
Send requests to the server and how to process the server response.
The simplest request is not to query parameters or send any information to the server by submitting form data. In practice, we all want to send some information to the server.
The basic steps for sending a request using the XMLHTTPRequest object are as follows:
A. To get a reference to the XMLHTTPRequest object, you can create a new instance or access a variable containing the XMLHTTPRequest object.
B. Tell the XMLHTTPRequest object that will handle changes to the state of the XMLHTTPRequest object. To this end, set the onreadystatechange attribute of the object to a pointer to the JavaScript function.
C. Specify the request attributes. The open () method of the XMLHTTPRequest object specifies the request to be sent. The open () method has three parameters: one is a string indicating the method used (usually get or post); the other is a URL string indicating the target resource; the other is a Boolean value, indicates whether the request is asynchronous.
D. Send the request to the producer server. The send () method of the XMLHTTPRequest object sends the request to the specified target resource. The send () method accepts a parameter, usually a string or a DOM object. This parameter is sent to the target URL as part of the Request body. 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, null is used.
You need an instance of the XMLHTTPRequest object to tell it how to do it if the status changes, but also to tell it to send the request to and how to send the request, and finally to guide XMLHttpRequest to send the request.

Function pointer:
Similar to other variables, it only points to a function instead of strings, numbers, and even object instances. In javascrip, all functions are included in the address in the memory and can be referenced using the function name. This provides great flexibility. You can pass the function pointer as a parameter to other functions of callback, or store the function pointer in the attributes of an object.

3. Simple request example
Simpleresponse.html
<! 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>
<Meta http-equiv = "Content-Type" content = "text/html; charset = gb2312"/>
<Title> simple XMLHttpRequest </title>
<SCRIPT type = "text/JavaScript">
VaR XMLHTTP;

Function createxmlhttprequest (){
If (window. activexobject ){
XMLHTTP = new activexobject ("Microsoft. XMLHTTP ");
}
Else if (window. xnlhttprequest ){
XMLHTTP = new XMLHttpRequest ();
}
}

Function startrequest (){
Createxmlhttprequest ();
XMLHTTP. onreadystatechange = handlestatechange;
XMLHTTP. Open ("get", "simpleresponse. xml", true );
XMLHTTP. Send (null );
}

Function handlestatechange (){
If (XMLHTTP. readystate = 4 ){
If (XMLHTTP. Status = 200 ){
Alert ("the server replied with:" + XMLHTTP. responsetext );
}
}
}
</SCRIPT>
</Head>

<Body>
<Form action = "#">
<Input type = "button" value = "start basic asynchronous request" onclick = "startrequest ();"/>
</Form>
</Body>
</Html>

Simpleresponse. xml
Arbitrary text
51

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.