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.
Thank you for reading this article instantiating an instance of XMLHttpRequest using javascript's try…catch With URL http://x-tutorials.blogspot.com/2007/12/instantiating-instance-of.html. Also a time to read the other articles.


0 comments:
Write your comment for this article instantiating an instance of XMLHttpRequest using javascript's try…catch above!