Ajax - Browser Support
This lesson includes one of the largest hurdles for aspiring Ajax programmers: browser support. It would be nice if all the web browsers required the same Javascript code to use Ajax, but life isn't fair and you've got your work cut out for you!Ajax - Try/Catch Blocks of Code
To create this important Ajax object, you are going to have to use a special programming technique known as "try and catch". Basically it attempts to "try" a piece of code and if that piece causes an error it "catches" the error and keeps going. Normally when an error occurs the code will stop running, however, the "catch" eats up the error and lets the code continue.In the following code we are going to "try" three different ways to make a new XMLHttpRequest object. Every time we fail and get an error, we will catch the error and try the next a different command.
Note: If our "try" is successful then the "catch" code will not be run because it is only used when there is an error.
order.html Javacsript Code:
<html> <body> <script language="javascript" type="text/javascript"> <!-- //Browser Support Code function ajaxFunction(){ var ajaxRequest; // The variable that makes Ajax possible! try{ // Opera 8.0+, Firefox, Safari ajaxRequest = new XMLHttpRequest(); } catch (e){ // Internet Explorer Browsers try{ ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { try{ ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP"); } catch (e){ // Something went wrong alert("Your browser broke!"); return false; } } } } //--> </script> <form name='myForm'> Name: <input type='text' name='username' /> <br /> Time: <input type='text' name='time' /> </form> </body> </html>
- ajaxRequest = new XMLHttpRequest();
- ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
- ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");>
Most likely though, our variable ajaxRequest will now be set to whatever XMLHttpRequest standard the browser uses and we can start sending data to the server.
Ajax - That Browser Specific Code is Confusing
The code in this lesson was quite complex, but the good thing is that you can just copy and paste this code and don't really have to understand it. I bet you wish I would have told you that at the beginning of the lesson!The next lesson will teach you how to use your XMLHttpRequest object (which is currently stored in ajaxRequest variable) to communicate with the server.
0 comments:
Post a Comment