XMLHttpRequest object of Ajax

Source: Internet
Author: User
XMLHttpRequest object of Ajax
Write an example: retrieve a Hello Ajax string from the server.
HTML:
<Input type = "button" value = "ajax submit" onclick = "Ajax ();"/>
<Div id = "result">
</Div>

Js: defines Ajax functions to obtain data asynchronously.
1. Declare An XMLHttpRequest object
2. instantiate the XMLHttpRequest object
3. Call open () of the XMLHttpRequest object, set the URL and request method of the server, and determine whether the request is asynchronous.
4. register an asynchronous callback event. The server will receive Event Notifications. registering this event is equivalent to setting the callback function.
5. send a request. Call the send () method. You do not need to set the send parameter for a Get request.

<Script type = "text/javascript">
Var XmlHttpReq = null; // declare an XMLHttpRequest object
If (window. ActiveXObject) {// instantiate the XMLHttpRequest object
XmlHttpReq = new ActiveXObject ("Microsoft. XMLHTTP ");
} Else if (window. XMLHttpRequest ){
XmlHttpReq = new XMLHttpRequest ();
}
Function Ajax () {// defines the Ajax function, asynchronously acquires data, and calls it in The onclick event in the Button
XmlHttpReq. open ("Get", "Default. aspx", true); // sets the server URL and request method, and whether or not the server is asynchronous
XmlHttpReq. onreadystatechange = RequestCallBack; // register an asynchronous callback event. The server will receive Event Notifications. registering this event is equivalent to setting the callback function.
XmlHttpReq. send (); send the request and call the send () method. You do not need to set the send parameter or null for a Get request.
}
Function RequestCallBack () {// callback function, registered on the onreadystatechange event
If (XmlHttpReq. readyState = 4 ){
If (XmlHttpReq. Status = 200 ){
Document. getElementById ("result"). innerHTML = XmlHttpReq. responseText;
}
}
}
</Script>

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.