How to Create an XMLHttpRequest Object
XMLHttpRequest
is the mechanism for sending data to and retrieving data from the server with Ajax.
- Use the
XMLHttpRequest()
constructor to create the object, as shown here:var xmlhttp = newXMLHttpRequest();
- Use the XMLHttpRequest object in an HTML document, as shown here:
<!DOCTYPE HTML> <html> <head> <meta charset="UTF-8"> <script type="text/javascript" src="lib.js"></script> <script type="text/javascript"> function start() { if (window.XMLHttpRequest) { var xmlhttp = new XMLHttpRequest(); document.getElementById("Content").innerHTML = "<h1>Using XMLHttpRequest Object</h1>"; } else { var xmlhttp = false; document.getElementById("Content").innerHTML = "<h1>XMLHttp cannot be created!</h1>"; } } observeEvent(window, "load", function() { var btn = document.getElementById("btnStart"); observeEvent(btn, "click", start); }); </script> <title>XMLHttpRequest - HTML5 Method</title> </head> <body> <button id="btnStart">Start</button> <div id="Content"></div> </body> </html>
Code Explanation: This code attempts to create an XMLHttpRequest object using the XMLHttpRequest() constructor. If it succeeds, it writes out "Using XMLHttpRequest Object" to the body of the page. If it fails, it writes out "XMLHttp cannot be created!"