Ajax XMLHttpRequest Detailed

Source: Internet
Author: User
Tags first string http request string methods

The first applications xmlhttp Microsoft, IE (IE5), by allowing developers to extend their functionality within a Web page using XMLHTTP ActiveX components, developers can transfer data directly to or from the server without navigating from the current Web page. This feature is important because it helps to reduce the pain of stateless connections, and it also eliminates the need to download redundant HTML, thereby increasing the speed of the process. The response of Mozilla (Mozilla1.0 above and above NetScape7) is to create its own inherited XML proxy class: the XMLHttpRequest class. Konqueror (and Safari v1.2, also a khtml based browser) also supports XMLHttpRequest objects, and opera also supports v7.6x+ objects in later versions of XMLHttpRequest. For most cases, XMLHttpRequest objects are similar to XMLHTTP components, and methods and properties are similar, except that a small subset of properties are not supported.

Application of XMLHttpRequest:
The application of XMLHttpRequest object in JS
var xmlhttp = new XMLHttpRequest ();
The application of Microsoft's XMLHTTP component in JS
var xmlhttp = new ActiveXObject (microsoft.xmlhttp);
var xmlhttp = new ActiveXObject (msxml2.xmlhttp);
XMLHttpRequest Object method
/**
* Cross-browser XMLHttpRequest instantiation.
*/

if (typeof XMLHttpRequest = = ' undefined ') {
XMLHttpRequest = function () {
var msxmls = [' MSXML3 ', ' MSXML2 ', ' M Icrosoft ']
for (var i=0 i < msxmls.length; i++) {
Try {
return new ActiveXObject (msxmls[i]+ '). XMLHTTP ')
} catch (e) {}
}
throw new Error ("No XML component installed!")
}
}
function Createxmlhttprequest () {
try {
//attempt to create it "the Mozilla Way"
if window . XMLHttpRequest) {
return new XMLHttpRequest ();
}
//Guess Not-now the IE way
if window. ActiveXObject) {
return new ActiveXObject (Getxmlprefix () +.) XmlHttp ");
}
}
catch (ex) {}
return false;
};

XMLHttpRequest Object Method Method description
Abort () Stop the current request
getAllResponseHeaders () returns the complete headers as a string
getResponseHeader ("Headerlabel") returns a single header label as a string
Open ("Method", "URL" [, asyncflag[, "UserName" [, "Password"]]) sets the target URL, methods, and other parameters for pending requests
Send (content) request
setRequestHeader ("label", "value") sets the header and sends it along with the request

XMLHttpRequest Object Attribute Property Description
onReadyStateChange event triggers with state changes
ReadyState Object State (integer):
0 = not initialized
1 = in read
2 = Read
3 = in interaction
4 = Complete
ResponseText The server process returns a text version of the data
Responsexml a compatible DOM XML Document object that returns data to the server process
Status code returned by the status server, such as: 404 = "Found at end of file", 200 = "Success"
StatusText status text information returned by the server


XMLHttpRequest Use Experience

*
*author jouy.lu
*/
var xmlHttp; First, define a global domain variable to hold the object's reference;
function Createxmlhttprequest () {//The 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 the browser-compatible issue: The suggested 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/************************************xmlhttprequest *********************
Abort (): terminates the current request;
getAllResponseHeaders (): Returns HTTP so response header as key/value pairs;
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, and the method also contains another three optional parameters;
Send (content), sending a request to the server;
setRequestHeader ("header", "value"); Set the specified header to the supplied value. The open () must be invoked before any header is set.
Note:
void Open (String methods, String URLs, 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 provides the URL of the invoked resource. You can also pass a Boolean value that indicates whether the call is asynchronous or synchronous,
The default value is true, which means that the request is inherently asynchronous. If this argument is false, processing waits until the response is returned from the server. Because asynchronous calls are using Ajax
One of the main advantages, so if you set this argument to False, it is somewhat inconsistent with the original intention of using the XMLHttpRequest object. In some cases this, a parameter
Setting to False is also useful, such as you might want to validate user input before persisting the page. The last two arguments are self-explanatory, allowing you to specify a specific username and password.
void Send (Content): This method makes a specific request to the server. If the request is declared asynchronous, the method returns immediately, or it waits until it receives a response
So far. The parameter is optional, it can be an instance of a DOM object, an input stream, or a string. The content passed in to this object is sent as part of the request body.
void setRequestHeader (string header, String value): This method sets the value for a given header in the HTTP request. It has two parameters, the first string table
Shows the header to set, and the second string represents the value to be placed in the header. It needs to be explained that this method must be called after open (). Of all these methods, it is most likely to use
is open () and send (). The XMLHttpRequest object also has many properties that are useful when designing Ajax interactions.
void Abort (): As the name suggests, this method is to stop the request.
String getAllResponseHeaders (): The core functionality of this method should be familiar to Web application developers, and it will return a string that contains all the sound of HTTP requests
should be the preamble. 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 one you want to get
The header value and returns the value as a string.


******************************/
/******************************* Standard XMLHttpRequest Properties **********************
onReadyStateChange: This event handler is triggered when each state changes, and typically a JavaScript function is invoked.
ReadyState: 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 resolved to a DOM object.
Status: The HTTP status code of the server (200 corresponds ok,404 to not Found (not found), and so on).
The appropriate text for the Statustext:http status code (OK or not Found (not found), and so on).
***************************************************************************
*/

/********************* to see exactly how to send a request *******
The basic steps for sending a request using a XMLHttpRequest object are as follows:
1. Gets a reference to the XMLHttpRequest object instance, for which you can create a new instance or access a variable that contains a
XMLHttpRequest instance.
2. Tells the XMLHttpRequest object which function handles 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. Specifies the properties of the request. The XMLHttpRequest object's open () method specifies the request that will be issued. The open () method takes 3
arguments: One is a string indicating the method used (usually a get or post), the other is a string representing the URL of the target resource, and a Boolean value indicating whether the request is asynchronous.
4. Sends the request to the server. The Send () method of the XMLHttpRequest object transmits 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 passed as part of the request body to the
destination URL. When supplying parameters to the Send () method, make sure 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 very cool!)
Requests to the server are sent asynchronously, so the browser can continue to respond to user input and wait in the background for the server's response.
If you choose to sync, and if the server's response takes several seconds to arrive, the browser will be slow to perform
The wait period cannot respond to user input. As a result, the browser seems to be frozen, unable to respond to user input, and asynchronous
This can be avoided, so that the end user has a better experience, although the improvement is subtle, but it does make sense.
This allows the user to continue working and the server will process the previous request in the background. Can communicate with the server without interrupting the user
Workflows so that you can use a lot of technology to improve the user experience. For example, suppose you have an application that validates user input. Use
When the user fills in the fields on the input form, the browser can periodically send the form values to the server for verification.
Broken user, he can also continue to fill out the remaining form fields. If a validation rule fails, the user is immediately notified without
Must wait for the form to be sent to the server for processing to know that there are errors, which can greatly save the user's time, but also can reduce the clothing
Because you do not have to completely recreate the contents of the form when the form submission is unsuccessful.

Here are the security issues:
The XMLHttpRequest object is subject to the browser's security "sandbox." XMLHttpRequest all resources requested by the object
Must be in the same domain as the calling script. This security restriction makes the XMLHttpRequest object unable to request
Find resources outside the domain where the script resides. The strength of this security restriction varies by browser (see Figure 2-5). Internet Explorer
A warning appears stating that there may be a security risk, but the user can choose whether to continue making the request. Firefox is
will stop the request categorically and display an error message in the JavaScript console. Firefox does provide some JavaScript tips,
Enables XMLHttpRequest to request resources for external URLs as well. However, since these technologies are for 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.