instantiating an instance of XMLHttpRequest using javascript's try…catch ~ Ajax Training, Learn Ajax Video Tutorials Online, Ajax Examples
Ajax Training, Learn Ajax Video Tutorials Online, Ajax Examples: instantiating an instance of XMLHttpRequest using javascript's try…catch

instantiating an instance of XMLHttpRequest using javascript's try…catch

If Old version browsers (Internet Explorer 5 for Mac) doesn’t support ActiveX object for Ajax
The getHTTPObject function throws an error in that browser.

JavaScript has a useful control structure for situations like this called the
try...catch statement.It looks at the user-agent string of the browser and check
its name and version number. This is called browser sniffing. We can use you can use object detection to test only for the existence of ActiveX, not for a particular type of ActiveX object.
Using try…catch block statement, we can execute the code, if it doesn’t work, you can catch the error. The error won’t be displayed in the browser.

if (window.ActiveXObject) {
try {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
} catch(e) {
xhr = false;
}
}

The try block contains the attempt to assign an instance of the ActiveX
object to the variable xhr. If that doesn’t work, the catch block sets the
value to false.
The try...catch statement can be used to refine the getHTTPObject function
even further. Later versions of Internet Explorer can use a newer ActiveX
object to handle Ajax. Using a series of try...catch statements, you can
attempt to use the newest version and, if that fails, fall back to the older way:

if (window.ActiveXObject) {
try {
xhr = new ActiveXObject("Msxml2.XMLHTTP");
} catch(e) {
try {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
} catch(e) {
xhr = false;
}
}
}

The finished function look like this:


function getHTTPObject() {
var xhr = false;
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
} else if (window.ActiveXObject) {
try {
xhr = new ActiveXObject("Msxml2.XMLHTTP");
} catch(e) {
try {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
} catch(e) {
xhr = false;
}
}
}
return xhr;
}

After handling exception, we are instantiating an instance of XMLHttpRequest. Once we’ve created an object with getHTTPObject, its methods and properties will be the same regardless of whether it’s native or an ActiveX object.

Related Posts by Categories

2 comments:

George said...

What are the steps for handling concurrent requests in AJAX?

Arvind said...

I believe it can be done by creating the XMLHTTPRequest object from within an inner function, instead of creating a seperate function for making a new XmlHttprequest object withing the same page...

Hope this helps!!

Regards, :)

Useful Links on Adobe Flex

Your Ad Here

Latest Books on Adobe Flex