XMLHttpRequest parameters in Ajax

Source: Internet
Author: User
Xjax is not a new [url = javascript:;] TechnologyThe birth of [/url] actually represents the combination of several technologies to play their respective roles in the same collaboration.
It includes:
Use XHTML and [url = javascript:;] CSS[/Url] standard presentation;
Use dom for Dynamic Display and interaction;
Use [url = javascript:;] XML[/Url] and XSLT for data exchange and processing;
Use XMLHttpRequest for asynchronous data reading;
Finally, use JavaScript to bind and process all data.
Here I will only talk about the XMLHTTPRequest object:
As shown above, XMLHttpRequest is used for asynchronous data reading;
First, we need to create the [url = javascript:;] Object[/Url], for different browsers, the object is created [url = javascript:;] Method[/Url] is different.
[Url = javascript:;] Internet[/Url] explorer is introduced as an ActiveX object, called XMLHTTP.
For Internet Explorer, the method for creating XMLHttpRequest is as follows:
Xmlhttp_request = new activexobject ("msxml2.xmlhttp. 3.0"); // 3.0 or 4.0, 5.0
Xmlhttp_request = new activexobject ("msxml2.xmlhttp ");
Xmlhttp_request = new activexobject ("Microsoft. XMLHTTP ");
XMLHTTP versions may be different in different Internet Explorer browsers. To better be compatible with different versions of Internet Explorer browsers, we need to create the XMLHttpRequest class based on different versions of Internet Explorer browsers, above [url = javascript:;] Code[/Url] is the method for creating the XMLHttpRequest Class Based on Different Internet Explorer browsers.
For Mozilla? Netscape? Create XMLHttpRequest in Safari and other browsers as follows:
Xmlhttp_request = new XMLHttpRequest ();
If the server response does not contain the XML mime-type header, some Mozilla browsers may not be able to [url = javascript:;] Work[/Url]. To solve this problem, if the server response header is not text/XML, you can call other methods to modify the header.
Xmlhttp_request = new XMLHttpRequest ();
Xmlhttp_request.overridemimetype ('text/xml ');
In practical applications, to be compatible with browsers of different versions, the method for creating the XMLHttpRequest class is generally written as follows:

Try {
If (window. activexobject ){
For (VAR I = 5; I --){
Try {
If (I = 2 ){
Xmlhttp_request = new activexobject ("Microsoft. XMLHTTP ");
} Else {
Xmlhttp_request = new activexobject ("msxml2.xmlhttp." + I + ". 0 ");
}
Xmlhttp_request.setrequestheader ("Content-Type", "text/XML ");
Xmlhttp_request.setrequestheader ("Content-Type", "gb2312 ");
Break;
}
Catch (e ){
Xmlhttp_request = false;
}
}
} Else if (window. XMLHttpRequest ){
Xmlhttp_request = new XMLHttpRequest ();
If (xmlhttp_request.overridemimetype ){
Xmlhttp_request.overridemimetype ('text/xml ');
}
}
} Catch (e) {xmlhttp_request = false ;}

After defining how to handle the response, you need to send the request. You can call the open () and send () Methods of the HTTP request class as follows:
Xmlhttp_request.open ('get', URL, true); xmlhttp_request.send (null );
Is the first parameter of open () the HTTP request method? Get, post, or any method supported by the server you want to call. According to HTTP specifications, this parameter must be capitalized; otherwise, Some browsers (such as Firefox) may not be able to process requests.
The second parameter is the URL of the Request page.
The third parameter sets whether the request is in asynchronous mode. If it is true, the JavaScript function will continue to be executed without waiting for the server to respond. This is "[url = javascript:;] Ajax"A" in [/url ".
After using JavaScript to create an XMLHttpRequest class to send an HTTP request to the server, you need to decide what to do when the server receives the response. This tells the HTTP request object which JavaScript function is used to process the response. You can set the onreadystatechange attribute of the object to the name of the JavaScript function to be used, as shown below: xmlhttp_request.onreadystatechange = functionname;
Functionname is the name of the function created with JavaScript. Be sure not to write it as functionname (). Of course, you can also directly create the JavaScript code after onreadystatechange. For example:
Xmlhttp_request.onreadystatechange = function (){
// JavaScript code segment
};
In this function. First, check the Request status. Only when a complete server response has been received can the function process the response. XMLHttpRequest provides the readystate attribute to determine the server response.
The value of readystate is as follows:
0 (not initialized)
1 (loading)
2 (loaded)
3 (in interaction)
4 (finished)

So only when readystate = 4, a complete server response has been received can the function process the response. The Code is as follows:
If (http_request.readystate = 4 ){
// Receives the complete Server Response
} Else {
// Failed to receive the complete Server Response
}
When readystate = 4, a complete server response has been received. Then, the function checks the status value of the HTTP server response. For complete status values, see W3C documentation. When the HTTP server response value is 200, the status is normal.
After checking the Request status value and response HTTP status value, you can process the data obtained from the server. There are two ways to get the data: (1) return the server response in the form of a text string.
/01/19 XMLHttpRequest
/*
* Author jouy. Lu
*/
VaR XMLHTTP; // first define a fully-local variable to save the object reference;
Function createxmlhttprequest () {// This method is used to create an instance of the XMLHTTPRequest object.
If (window. activexobject ){
XMLHTTP = new activexobject ("Microsoft. XMLHTTP ");
} Else if (window. XMLHttpRequest ){
XMLHTTP = new XMLHttpRequest ();
}
}
Considering compatibility with browsers, the recommended method is as follows:
VaR XMLHTTP;
Function createxmlhttp (){
If (window. XMLHttpRequest ){
XMLHTTP = new XMLHttpRequest ();
If (XMLHTTP. overridemimetype ){
XMLHTTP. overridemimetype ("text/XML ");
}

}
Else if (window. activexobject ){
Try {
XMLHTTP = new activexobject ("msxml2.xmlhttp ");
} Catch (e ){
XMLHTTP = new activexobject ("Microsoft. XMLHTTP ");
}
}
If (! XMLHTTP ){
Window. Alert ("Your broswer not support XMLHttpRequest! ");
}
Return XMLHTTP;
}
/*********************************** XMLHttpRequest Standard operation *********************
Abort (): Terminate the current request;
GetAllResponseHeaders (): return the HTTP Response Header as a key/value pair;
GetResponseHeader ("Header"); returns the string value of the specified header;
Open ("post/get/put", "url"); creates a call to the server. The URL parameter can be relative or absolute URL, this method also contains three other optional parameters;
Send (content); send a request to the server;
SetRequestHeader ("Header", "value"); set the specified header to the provided value. You must call open () before setting any header ().
Note:
Void open (string method, string URL, Boolean asynch, string username, string password): This method creates a call to the server.
You must provide the specific method (get, post, or put) to be called and the URL of the called resource. In addition, a Boolean value can be passed to indicate whether the call is asynchronous or synchronous. The default value is true, which indicates 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 one of the main advantages of using Ajax. Therefore, if this parameter is set to false, it is not consistent with the original intention of using the XMLHTTPRequest object to some extent. In some cases, setting this parameter to false is also useful. For example, you may want to verify user input before the persistent storage page. The last two parameters are self-explanatory and allow you to specify a specific user name and password.
Void send (content): This method sends a request to the server. If the request is declared as Asynchronous, this method will return immediately, otherwise it will wait until the response is received. The parameter is optional. It can be an instance of a DOM object, an input stream, or a string. The content of this object will be sent as part of the Request body.
Void setRequestHeader (string header, string value): This method sets the value of 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. Among all these methods, open () and send () are most likely to be used (). The XMLHTTPRequest object also has many attributes that are useful when designing Ajax interactions.
Void abort (): As the name suggests, this method is to stop the request.
String getAllResponseHeaders (): the core function of this method should be familiar to Web application developers. It will return a string containing all Response Headers of HTTP requests. The header includes Content-Length, date, and Uri.
String getResponseHeader (string header): This method corresponds to getAllResponseHeaders (), but it has a parameter to indicate which header value you want to obtain, this value is returned as a string.
******************************/
/*************** Standard XMLHttpRequest attributes******************
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, 4 = complete.
Responsetext: server response, which is a string.
Responsexml: Server Response, expressed as XML. This object can be parsed into a DOM object.
Status: the HTTP status code of the server (200 corresponds to OK, 404 corresponds to not found (not found), and so on ).
Statustext: the text of the HTTP status code (OK or not found (not found ).
**************************************** *********************/
/******************** To see how to send a request *******
Follow these steps to send a request using the XMLHTTPRequest object:
1. Get a reference to the XMLHTTPRequest object instance. To do this, you can create a new instance or access
A variable of the XMLHttpRequest instance.
2. Tell the XMLHTTPRequest object which function will handle changes to the state of the XMLHTTPRequest object. Therefore, you need to set the onreadystatechange attribute of the object to a pointer to a JavaScript function.
3. Specify the request attributes. The open () method of the XMLHTTPRequest object specifies the request to be sent. 3 For the open () method
Parameter: A string indicating the method used (usually get or post), a string indicating the URL of the target resource, and
Boolean value, indicating whether the request is asynchronous.
4. Send the request to the server. The send () method of the XMLHTTPRequest object sends the request to the specified target resource.
The send () method accepts a parameter, which is usually a string or a DOM object. This parameter is transmitted 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.
The experience that asynchronous mode brings to users: (I think it's really nice for programmers to see this explanation !)
Requests sent to the server are sent asynchronously. Therefore, the browser can continue to respond to user input and wait for the server's response in the background.
If you select a synchronization operation and the server response takes several seconds to arrive, the browser will be very slow.
The user input cannot be responded during the waiting period. In this way, the browser seems to be frozen and cannot respond to user input while being asynchronous.
This can be avoided to give end users a better experience. Although this improvement is subtle, it is indeed meaningful.
In this way, the user can continue to work, and the server will process previous requests in the background. Which can communicate with the server without interrupting the user
Workflow to improve user experience. For example, assume there is an application that verifies user input. Use
When entering fields in the input form, the browser can periodically send the form value to the server for verification.
The user is disconnected, and he can continue to fill in the remaining form fields. If a validation rule fails, the user will be notified immediately
It is required to know the error only when the form is actually sent to the server for processing, which can greatly save the user's time and reduce the server
Load Pressure on the server, because you do not have to completely recreate the content of the form when the form is not submitted successfully.
The following describes the security issues:
The XMLHTTPRequest object is subject to the browser's security "sandbox ". All resources requested by the XMLHTTPRequest object
Must be in the same domain as the calling script. This security restriction makes the XMLHTTPRequest object unavailable
Find resources outside the domain where the script is located. The intensity of this security restriction varies with the browser (see Figure 2-5 ). Internet Explorer
A warning is displayed, indicating that there may be a security risk, but the user can choose whether to continue sending the request. In Firefox
Stop the request and display an error message in the Javascript console. Firefox does provide some JavaScript skills so that XMLHttpRequest can also request external URL resources. However, because these technologies are applicable to specific browsers, it is best not to use them, and avoid using XMLHttpRequest to access external URLs.
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.