Go: xhr object in Ajax

Source: Internet
Author: User
Tags first string xslt

Xjax is not the birth of a new technology. It actually represents a combination of several technologies in a way that plays their part in a common collaboration.
It includes:
Standardized rendering using XHTML and CSS;
Use the DOM for dynamic display and interaction;
Data exchange and processing using XML and XSLT;
Using XMLHTTPR
Xjax is not the birth of a new technology. It actually represents a combination of several technologies in a way that plays their part in a common collaboration.
It includes:
Standardized rendering using XHTML and CSS;
Use the DOM for dynamic display and interaction;
Data exchange and processing using XML and XSLT;
Asynchronous data reading using XMLHttpRequest;
Finally, all data is bound and processed with JavaScript.

Here I'm only talking about the XMLHttpRequest object:

As seen above, asynchronous data reads are performed using XMLHttpRequest;

First, we're going to create this object, and for different browsers, there's a difference in how the object is created.
Internet Explorer is introduced as an ActiveX object, known as XMLHTTP.

For the Internet Explorer browser, create the XMLHttpRequest method 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 inconsistent in different Internet Explorer browsers, in order to be better compatible with different versions of Internet Explorer browsers, so we need to use different versions of the Internet Explorer browser to create the XMLHttpRequest class, the above code is the method of creating the XMLHttpRequest class based on the different Internet Explorer browsers.


For Mozilla? Netscape? For browsers such as Safari, create the XMLHttpRequest method as follows:

Xmlhttp_request = new XMLHttpRequest ();
Some Mozilla browsers may not work correctly if the server's response does not have an XML Mime-type header. 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 practice, in order to be compatible with many different versions of browsers, the method of creating the XMLHttpRequest class is generally written in the following form:

try{
if (window. ActiveXObject) {
for (var i = 5; i; 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 you have defined how the response is handled, the request is sent. You can invoke the open () and send () methods of the HTTP request class as follows:

Xmlhttp_request.open (' GET ', URL, true); Xmlhttp_request.send (NULL);

The first parameter of open () is the HTTP request method? Get,post or any server that supports the way you want to call. This parameter is capitalized according to the HTTP specification, otherwise some browsers, such as Firefox, may not be able to process the request.


The second parameter is the URL of the requested page.

The third parameter sets whether the request is asynchronous mode. If the True,javascript function continues execution, it does not wait for the server to respond. This is the "a" in "AJAX".


After you use JavaScript to create a XMLHttpRequest class to send an HTTP request to the server, you decide what to do when you receive a response from the server. This requires telling the HTTP request object which JavaScript function to use to handle the response. You can set the object's onReadyStateChange property to the function name of the JavaScript that you want to use, as follows: Xmlhttp_request.onreadystatechange =functionname;


FunctionName is a function name created with JavaScript, be careful not to write functionname (), and of course we can create JavaScript code directly after onreadystatechange, for example:

Xmlhttp_request.onreadystatechange = function () {
JavaScript Code Snippets
};


In this function. The first thing to check is the status of the request. The function can handle the response only if a full server response has been received. XMLHttpRequest provides the ReadyState property to judge the server response.

The values of the readystate are as follows:

0 (uninitialized)

1 (loading)

2 (Loading complete)

3 (in interactive)

4 (complete)

So only when readystate=4, a full server response has been received, can the function handle the response. The specific code is as follows:

if (http_request.readystate = = 4) {
Receive the full server response
} else {
Did not receive the full server response
}


When readystate=4, a full server response has been received, and then the function checks the status value of the HTTP server response. The full status value can be found in the documentation. When the HTTP server responds with a value of 200, it indicates that the status is OK.

After you have checked the status value of the request and the HTTP status value of the response, you are ready to process the data obtained from the server. There are two ways to get this data: (1) Returns the server's response as a text string.

2006/01/19xmlhttprequest detailed


/*
*author jouy.lu
*/
var xmlHttp; First, a global domain variable is defined to hold the object's 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 ();
}
}

Consider a browser-compatible issue: The recommended wording 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;
}

Standard operation of the/************************************xmlhttprequest *********************
Abort (): terminates the current request;
getAllResponseHeaders (): Returns HTTP so the response header is returned as a key/value pair;
getResponseHeader ("header"); Returns the string value of the specified header;
Open ("Post/get/put", "url"), establish a call to the server, the URL parameter can be a relative URL or an absolute URL, the method also contains another three optional parameters;
Send a request to the server;
setRequestHeader ("header", "value"); Sets the specified header to the provided value. The open () must be called before any headers can be set.
Note:
void Open (String method, String url, Boolean asynch, string Username, string password): This method establishes a call to the server.
To provide a specific method of invocation (GET, post, or put), also provide the URL of the resource being invoked. You can also pass a Boolean value indicating whether the call is asynchronous or synchronous and the default value is true, which means that the request is inherently asynchronous. If this parameter is false, the processing waits until the response is returned from the server. Because asynchronous invocation is one of the main advantages of using AJAX, setting this parameter to False is somewhat inconsistent with the original intention of using the XMLHttpRequest object. In some cases, it is also useful to set a parameter to false, such as you might want to validate the user's input before persisting the page. The last two parameters are self-explanatory, allowing you to specify a specific user name and password.
void Send (Content): This method makes a specific request to the server. If the request is declared asynchronous, the method returns immediately, otherwise it waits until the response is received. Parameters are optional and can be an instance of a DOM object, an input stream, or a string. The contents of the incoming object are sent as part of the request body.
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 represents the header to be set, and the second string represents the value to be placed in the header. It needs to be stated that this method must be called after open (). Of all of these methods, the most likely to be used is open () and send (). The XMLHttpRequest object also has many properties that are useful when designing Ajax interactions.
void Abort (): As the name implies, this method is to stop the request.
String getAllResponseHeaders (): The core functionality of this approach should be familiar to Web application developers, and it will return a string that contains all the response headers for the HTTP request. The header includes Content-length, date, and URI.
String getResponseHeader (String header): This method corresponds to getAllResponseHeaders (), but it has a parameter that indicates which header value you want to get, and returns the value as a string.
******************************/

/*************** Standard XMLHttpRequest Property ******************
onReadyStateChange: This event handler is triggered when each state changes, and a JavaScript function is usually called.
ReadyState: The status of the request. There are 5 desirable values: 0 = uninitialized, 1 = loading, 2 = loaded, 3 = interactive, 4 = complete.
ResponseText: The response of the server, expressed as a string.
Responsexml: The response of the server, expressed as XML. This object can be parsed as a DOM object.
Status: The HTTP status code for the server (200 corresponds to ok,404 not Found (not found), and so on).
Statustext:http the corresponding text for the status code (OK or not Found (not found), and so on).
*************************************************************/

/********************* to see how you can send a request *******
The basic steps for sending a request using the XMLHttpRequest object are as follows:
1. Get a reference to the XMLHttpRequest object instance, you can create a new instance, or access a
A variable of the XMLHttpRequest instance.
2. Tell the XMLHttpRequest object which function will handle changes to the state of the XMLHttpRequest object. To do this, set the object's onReadyStateChange property to a pointer to a JavaScript function.
3. Specify the properties of the request. The open () method of the XMLHttpRequest object specifies the request that will be made. The open () method takes 3 parameters: one is the string that indicates which method is used (usually get or post), the other is a string that represents the URL of the target resource, and a Boolean value that indicates whether the request is asynchronous.
4. Send the request to the server. The Send () method of the XMLHttpRequest object transmits the request to the specified target resource.
The Send () method takes a parameter, which is usually a string or a DOM object. This parameter is passed to the destination URL as part of the request body. When supplying parameters to the Send () method, ensure that the method specified in open () is post. If no data is to be sent as part of the request body, NULL is used.

Asynchronous way to the user experience: (I think the programmer to see this explanation, the heart is really cool!)
Requests to the server are sent asynchronously, so the browser can continue to respond to user input and wait for the server's response in the background.
If you choose to synchronize, and if the response of the server takes several seconds to arrive, the browser behaves very slowly and cannot respond to the user's input during the wait. In this way, the browser seems to be frozen, unable to respond to user input, and asynchronous practices can avoid this situation, so that the end user has a better experience, although this improvement is very small, but it does make sense.
This allows the user to continue working, and the server processes the previous request in the background. The ability to communicate with the server without interrupting the user's workflow, so that many techniques can be used to improve the user experience. For example, suppose you have an app that validates user input. When the user fills in the fields on the input form, the browser can periodically send form values to the server for validation without interrupting the user, and he can continue to fill in the remaining form fields. If a validation rule fails, the user is immediately notified without having to wait until the form is actually sent to the server for processing to know that there is an error, which can greatly save the user's time and reduce the load on the server because it does not have to completely rebuild the contents of the form when the form submission is unsuccessful.

Here's a description of the security issue:
The XMLHttpRequest object is subject to the browser's security "sandbox". All resources requested by the XMLHttpRequest object must be within the same domain as the calling script. This security restriction makes the XMLHttpRequest object unable to request resources outside the domain of the script. How the strength of this security limit varies by browser (see Figure 2-5). Internet Explorer
A warning is displayed stating that there may be a security risk, but the user can choose whether to continue making the request. Firefox stops the request outright and displays an error message in the JavaScript console. Firefox does provide some JavaScript tricks that allow XMLHttpRequest to request resources for external URLs as well. However, because these technologies are specific to browsers, it is best not to use them and to avoid using XMLHttpRequest to access external URLs.

Go: xhr object in Ajax

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.