Introduction to XMLHttpRequest Properties and methods

Source: Internet
Author: User
Tags format object definition header object model string version variable

1, what is the XMLHttpRequest object?
2, create the XMLHttpRequest object.
3, XMLHttpRequest properties and methods.

1, what is the XMLHttpRequest object?

The most common definition is: XMLHTTP is a set of APIs that can be routed through HTTP protocols or receive XML and other data from a scripting language such as JavaScript, VbScript, and JScript. The biggest use of XMLHTTP is that you can update portions of a Web page without refreshing the entire page. (This feature is one of the big features of Ajax:)

Explanation from MSDN: XMLHTTP provides a protocol for clients to communicate with HTTP servers. The client can pass the XMLHTTP object (MSXML2). xmlhttp.3.0) Send a request to the HTTP server and use the Microsoft XML Document Object model Microsoft? The XML Document Object Model (DOM) handles the response.

Here to say some digression, in fact this thing very early appeared, but the previous browser support is not enough, only IE support, so most of the web programmer did not use him, but now the situation has changed greatly, Mozilla and Safari to use it as a de facto standard, Mainstream browsers are beginning to support XMLHttpRequest objects. But the point here is that XMLHttpRequest is not currently a standard for the world of the web, so there are slightly different browsers.

2. Create XMLHttpRequest objects

By the way, when it comes to the difference, let's look at how to declare (use) it, and before sending the request and processing the response using the XMLHttpRequest object, we have to create a XMLHttpRequest object with JavaScript. (ie implements XMLHttpRequest as an ActiveX object, and other browsers [such as Firefox/safari/opear] implement it as a local JavaScript object). Let's take a look at how to use JavaScript specifically to create it:

<script language= "javascript" type= "Text/javascript" >
<!--
var xmlhttp;
Creating XMLHttpRequest Objects
function Createxmlhttprequest () {
if (window. ActiveXObject) {//Determine if ActiveX controls are supported
XMLHTTP = new Activeobject ("Microsoft.XMLHTTP"); To create a XMLHttpRequest object by instantiating a new instance of ActiveXObject
}
else if (window. XMLHttpRequest) {//To determine whether to implement XMLHttpRequest as a local JavaScript object
XMLHTTP = new XMLHttpRequest (); Create an instance of the XMLHttpRequest (local JavaScript object)
}
}
-->
</script>

3, properties and methods

Because there are too many things now first use a page to enumerate the methods and attributes, and then to give detailed examples (mainly I also in the study).

Description of the <title>xmlhttprequest object demo</title>
<script language= "javascript" type= "Text/javascript" >
<!--
var xmlhttp;
Create a XMLHttpRequest Object
function Createxmlhttprequext () {
if (window. ActiveXObject) {
XMLHTTP = new ActiveXObject (' microsoft.xmlhttp ');
}
else if (window. XMLHttpRequest) {
XMLHTTP = new XMLHttpRequest ();
}
}
function Postorder (xmldoc)
{
Createxmlhttprequext ();

Method: Open
Creates a new HTTP request and specifies the method, URL, and authentication information for this request
Grammar: Oxmlhttprequest.open (Bstrmethod, bstrURL, Varasync, Bstruser, bstrpassword);
Parameters
Bstrmethod
HTTP methods, for example: POST, get, put, and propfind. Not sensitive to case.
bstrURL
The URL address of the request, which can be either an absolute address or a relative address.
varasync[Optional]
Boolean, specifying whether this request is asynchronous and true by default. If true, the callback function specified by the onReadyStateChange property is invoked when the state changes.
bstruser[Optional]
If the server requires authentication, the user name is specified here, and if not specified, the validation window pops up when the server needs to authenticate.
bstrpassword[Optional]
The password portion of the authentication information, which is ignored if the user name is empty.

Note: After calling this method, you can call the Send method to send data to the server.
xmlHTTP. Open ("Get", "http://localhost/example.htm", false);
var book = Xmlhttp.responseXML.selectSingleNode ("//book[@id = ' bk101 ']");
alert (book.xml);


Properties: onReadyStateChange
onReadyStateChange: Specifies the event handling handle when the ReadyState property changes
Grammar: Oxmlhttprequest.onreadystatechange = Funcmyhandler;
The example below shows that the Handlestatechange function is invoked when the ReadyState property of the XMLHttpRequest object is changed.
Once the data has been received (readystate = 4) A button on this page will be activated
Note: This property is written only and is an extension of the Document Object model for the consortium.
Xmlhttp.onreadystatechange= Handlestatechange;

Method: Send
Send request to HTTP server and receive response
Grammar: Oxmlhttprequest.send (varbody);
Parameters: Varbody (data to be sent through this request). )
Note: This method is synchronized or asynchronous depending on the Basync parameter in the open method, and if Basync = = False, this method will wait for the request to complete or time out to return, and if Basync = = True, this method returns immediately.
This method takes one optional parameter, which are the requestbody to use. The acceptable VARIANT input types are BSTR, SAFEARRAY of UI1 (unsigned bytes), IDispatch to an XML Document Object Model (DOM) object, and IStream *. can use only chunked encoding (for sending) when sending IStream * input types. The component automatically sets the Content-length header for all but IStream * input types.
If the data sent is BSTR, the response is encoded as utf-8 and a document type header containing CharSet must be set in place.
If the input type is a SAFEARRAY of UI1, the response are sent as is without additional. The caller must set a Content-type header with the appropriate Content Type.
If the data sent is XML DOM object, the response is encoded as the encoding declared in the XML document, and the default UTF-8 is used if no encoding is declared in the XML document.
If the input type is a IStream *, the response is sent as is without additional encoding. The caller must set a Content-type header with the appropriate Content Type.
xmlHTTP. Send (xmldoc);

Method: getAllResponseHeaders
Gets all HTTP headers for the response
Syntax: strvalue = Oxmlhttprequest.getallresponseheaders ();
Note: Each HTTP header name and value is separated by a colon and ends with \ r \ n. The method cannot be called until the Send method completes.
Alert (Xmlhttp.getallresponseheaders ());
Method: getResponseHeader
Gets the specified HTTP header from the response information
Syntax: strvalue = Oxmlhttprequest.getresponseheader (Bstrheader);
Note: This method can only be invoked when the Send method succeeds. If the server returns a document type of "Text/xml", this sentence
Xmlhttp.getresponseheader ("Content-type"); the string "Text/xml" will be returned. You can use the getAllResponseHeaders method to get complete HTTP header information.
Alert (Xmlhttp.getresponseheader ("Content-type")); The Content-type column in the output HTTP header: The version and name of the current Web server.


Document.frmTest.myButton.disabled = true;
Method: Abort
Cancel the current request
Syntax: Oxmlhttprequest.abort ();
Note: When this method is called, the current request returns the uninitialized state.
Xmlhttp.abort ();

Method: setRequestHeader
Specify an HTTP header for the request individually
Grammar: Oxmlhttprequest.setrequestheader (Bstrheader, Bstrvalue);
Parameters: Bstrheader (string, header name. )
Bstrvalue (string, value. )
Note: If an HTTP header with this name already exists, it is overwritten. This method must be called after the Open method.
Xmlhttp.setrequestheader (Bstrheader, Bstrvalue);
}
function Handlestatechange ()
{
Properties: ReadyState
Returns the current status of the XMLHTTP request
Grammar: LValue = oxmlhttprequest.readystate;
Note: variable, this property is read-only and the state is represented by an integer of length 4. The definition is as follows:
0 (uninitialized) object established, but not initialized (the open method has not been called)
1 (initialization) object established, send method has not been called
2 (send data) The Send method has been invoked, but the current state and HTTP headers are unknown
3 (data transfer) has received part of the data, because the response and HTTP headers are incomplete, then get some data through Responsebody and ResponseText error,
4 (complete) data received, at this time through Responsebody and responsetext to obtain complete response data
if (xmlhttp.readystate = = 4) {
document.frmTest.myButton.disabled = false;

Properties: Responsebody
Returns the server response data in a format
Grammar: strvalue = oxmlhttprequest.responsebody;
Note: variable, this property is read-only, in unsigned array format to represent the decoded binary data that is returned directly from the server.
alert (xmlhttp.responsebody);

Properties: Responsestream
Returns the response information as an ADO Stream object
Grammar: strvalue = Oxmlhttprequest.responsestream;
Note: variable, this property is read-only and returns the response information as an ADO Stream object.
alert (Xmlhttp.responsestream);

Properties: ResponseText
Returns the response information as a string
Grammar: strvalue = Oxmlhttprequest.responsetext;
Note: variable, this property is read-only, and the response information is returned as a string. XMLHTTP attempts to decode the response information into a Unicode string.
XMLHTTP The response data is encoded as UTF-8 by default, and if the server returns data with a BOM (Byte-order Mark), XMLHTTP can
To decode any UCS-2 (big or little endian) or UCS-4 data. Note that if the server returns an XML document, this is
Sex does not process the encoding declaration in an XML document. You need to use Responsexml to handle it.
alert (Xmlhttp.responsetext);

Properties: Responsexml
Formats the response information as an XML Document object and returns
Syntax: var objdispatch = oxmlhttprequest.responsexml;
Note: variable, this property is read-only, and the response information is formatted as an XML Document object and returned. If the response data is not a valid XML document,
This property does not return Xmldomparseerror itself, and can get the error message through the processed DOMDocument object.
Alert ("result =" + Xmlhttp.responseXML.xml);

Properties: Status
Returns the HTTP status code for the current request
Grammar: LValue = oxmlhttprequest.status;
Return value: Long shaping standard HTTP status code, defined as follows:
Number:description
100:continue
101:switching protocols
200:ok
201:created
202:accepted
203:non-authoritative Information
204:no Content
205:reset Content
206:partial Content
300:multiple Choices
301:moved Permanently
302:found
303:see Other
304:not Modified
305:use Proxy
307:temporary Redirect
400:bad Request
401:unauthorized
402:payment Required
403:forbidden
404:not Found
405:method not allowed
406:not acceptable
407:proxy Authentication Required
408:request Timeout
409:conflict
410:gone
411:length Required
412:precondition Failed
413:request Entity Too Large
414:request-uri Too Long
415:unsupported Media Type
416:requested Range Not suitable
417:expectation Failed
500:internal Server Error
501:not implemented
502:bad Gateway
503:service unavailable
504:gateway Timeout
505:http Version not supported
Note: Long shaping, this property is read-only, returns the HTTP status code for the current request, which is only available when the data is sent and received.
alert (xmlhttp.status);

Properties: StatusText
Returns the response line status of the current request
Grammar: strvalue = Oxmlhttprequest.statustext;
Note: String, this property is read-only to BSTR returns the response row state of the current request, which is only available if the data is sent and received.
alert (Xmlhttp.statustext);
}
}
-->
</script>
<body>
<form name= "Frmtest" >
<input name= "MyButton" type= "button" value= "click Me" >
</form>
</body>


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.