AJAX & Prototype Ajax Features Needed to Build Active Client Pages |
The XMLHttpRequest Object By using the XMLHttpRequest object, a web developer can update a page with data from the server after the page has loaded! The XMLHttpRequest object is supported in Internet Explorer 5.0+, Safari 1.2, Mozilla 1.0 / Firefox, Opera 8+, and Netscape 7. Ajax Browsers The keystone of AJAX is the XMLHttpRequest object. Different browsers use different methods to create the XMLHttpRequest object. Internet Explorer uses an ActiveXObject, while other browsers uses the built-in JavaScript object called XMLHttpRequest. All Ajax requests in JavaScript begin by making a call to the XMLHttpRequest constructor function: new XMLHttpRequest() //IE7, Firefox, Safari etc; new ActiveXObject("Msxml2.XMLHTTP") //newer versions of IE5+; new ActiveXObject("Microsoft.XMLHTTP") //older versions of IE5+; new XDomainRequest() //IE8+ only. A more "secure", versatile alternative to IE7's XMLHttpRequest() object. In IE6 and below, the XMLHttpRequest() is not supported, but instead relies on the proprietary ActiveXObject for Ajax requests. To create this object, and deal with different browsers, we are going to use a "try and catch" statement. This is a typical way to address the problem (the explanation is given below): <html> <body> <script type="text/javascript">function ajaxFunction() { var xmlHttp; try { // Firefox, Opera 8.0+, Safari xmlHttp=new XMLHttpRequest(); } catch (e) { // Internet Explorer try { xmlHttp=new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { try { xmlHttp=new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) { alert("Your browser does not support AJAX!"); } } } } </script> </body> </html> Explanation In this illustration, the function you write that handles Ajax request is called ajaxFunction. First we need to create a variable xmlHttp to hold the XMLHttpRequest object in the function. Then we try to create the object with XMLHttp=new XMLHttpRequest(). This is for Firefox, Opera, and Safari browsers. If that fails, we try xmlHttp=new ActiveXObject("Msxml2.XMLHTTP"), which is for Internet Explorer 6.0+. If that also fails, we try xmlHttp=new ActiveXObject("Microsoft.XMLHTTP"), which is for Internet Explorer 5.5+. If none of the three methods work, the user has a very outdated browser, and he or she will get an alert stating that the browser doesn't support AJAX. Note: The browser-specific code above is long and quite complex. However, you can use this code every time you need to create an XMLHttpRequest object. The code above is compatible with all of the popular browsers: Internet Explorer, Opera, Firefox, and Safari.
blog comments powered by Disqus |
|
|
|
|
|
|
|