Using XMLHttpRequest with DOM objects

Source: Internet
Author: User
Tags first string header http request object model tag name tagname unique id window
dom|request|xml|xmlhttprequest| objects XMLHttpRequest Objects

Before you can use the XMLHttpRequest object to send a request and process a response, you must first create a XMLHttpRequest object with JavaScript. Since XMLHttpRequest is not a standard for the consortium, there are several ways to use JavaScript to create instances of XMLHttpRequest. IE implements an ActiveX object for XMLHttpRequest, and other browsers (such as Firefox, Safari, and Opera) implement it as a local JavaScript object. Because of these differences, JavaScript code must contain relevant logic to use ActiveX technology or use local JavaScript object technology to create a XMLHttpRequest case.

If your browser supports ActiveX objects, you can use ActiveX to create XMLHttpRequest objects. Otherwise, the local JavaScript object technology will be used to create it. Code Listing 2-1 shows the scripting of Cross-browser JavaScript code to create XMLHttpRequest object instances.

Code Listing 2-1 creates an instance of the XMLHttpRequest object
var xmlHttp;
function Createxmlhttprequest () {
if (window. ActiveXObject) {
XmlHttp = new ActiveXObject ("Microsoft.XMLHTTP");
}else if (window. XMLHttpRequest) {
XmlHttp = new XMLHttpRequest ();
}
}
As you can see, creating XMLHttpRequest objects is fairly easy. First, you create a global scope variable XMLHTTP to hold the reference to this object. The Createxmlhttprequest method completes the specific work of creating a XMLHttpRequest instance. This method has only simple branching logic (selection logic) to determine if the object is created. To window. A ActiveXObject call returns an object, or a null,if statement that returns the result of the call as True or False (False if the return object is true) to indicate whether the browser supports ActiveX controls. It is appropriate to know that the browser is ie. If it is, the XMLHttpRequest object is created by instantiating a new instance of ActiveXObject and passing in a string indicating what type of ActiveX object to create. In this example, the string provided for the constructor is Microsoft.XMLHTTP, which indicates that we want to create an instance of the XMLHttpRequest.

If window. ActiveXObject call fails (returns NULL), JavaScript will go to the Else statement branch to determine whether the browser implements XMLHttpRequest as a local JavaScript object. If there is a window. XMLHttpRequest, an instance of XMLHttpRequest is created.

properties of the XMLHttpRequest object:
onReadyStateChange event triggers with state changes
ReadyState Object State (integer): 0 = uninitialized 1 = read 2 = Read 3 = Interactive 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 = "File not found", 200 = "Success"
StatusText status text information returned by the server

Ways to XMLHttpRequest objects:
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

Detailed description of the method:
void Open (String method,string url,boolean asynch,string username,string password):
This method establishes a call to the server. This is a pure scripting method that initializes a request with two necessary parameters and 3 optional parameters. 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 indicating whether the call is asynchronous or synchronous. The default value is true to indicate that the request is inherently asynchronous. If this argument is false, processing waits until the response is returned from the server. Because asynchronous invocations are one of the main advantages of using AJAX, if this argument is set to False, the XMLHttpRequest object's original intent is not quite the same. However, as mentioned earlier, it is useful to set this parameter to false in some cases, such as validating the user's 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, otherwise it waits until the response is received. An optional parameter can be an instance of a DOM object, an input stream, or a string. The content passed into this method is sent as part of the request body.

void Serrequestheader (String header,string value):
This method sets the value for a specified header in the HTTP request. He has two parameters, the first string represents the header to set, and the second string represents the value to be placed in the header. It needs to be explained that the content of this method is sent as part of the request body.

void Abort ():
As the name suggests, this method is to stop the request.

string getAllResponseHeaders ():
The core functionality of this approach should be familiar to Web application developers, which returns a string that contains all the response headers for HTTP requests, including ContentLength, date, and URI.

string getResponseHeader (string header):
This method corresponds to the getAllResponseHeaders (), but it has a parameter that represents the specified header value you want to get and returns the value as a string.

DOM Object

The Document Object model is a platform-and language-independent interface that allows programs and scripts to dynamically access and update the content, structure, and style of a document. The document can be processed further, and the resulting processing can be put back in the provided page. If the server returns XML, use Responsexml to create the DOM directly to manipulate the file.
ChildNodes returns the collection of all child elements of the current element
Firstchil returns the first child element of the current element
LastChild returns the last child element of the current element
NextSibling returns the element immediately following the current element (peer)
PreviousSibling returns the element immediately preceding the current element (peer)
NODEVALUE specifies a read/write property that represents the value of an element
ParentNode returns the parent node of the element

methods of Dom objects:
getElementById (ID) (document) Gets the elements in the document with the specified unique id attribute value
getElementsByTagName (name) returns a collection of child elements in the current element that have the specified tag name
HasChildNodes () returns a Boolean value indicating whether the element has child elements
GetAttribute (name) returns the attribute value of the element, which is specified by name

the Consortium DOM properties and methods used to dynamically create content
The CreateElement method on the document.createelement (tagName) Document object can create elements that are specified by TagName. If the string div is used as a method parameter, a DIV element is generated
The createTextNode method of the document.createTextNode (text) Document object creates a node that contains static text
The Element.appendchild (Childnode) AppendChild method adds the specified node Childnode to the list of child nodes of the current element
Element.getattribut (name)
Element.setattribut (name, value) gets and sets the value of the Name property in the element
Element.insertbefore (NewNode, TargetNode) This method inserts the node NewNode in front of the targetnode element as a child of the current element
Element.removeattribute (name) removes property name from the element
Element.removechild (Childnode) deletes a child element from the element Childnode
Element.replacechild (Newnode,oldnode) replaces the node OldNode with a node NewNode
Element.haschildnodes () returns a Boolean value indicating whether the element has child elements

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.