XML.com: Errors and AJAX:
XMLHttpRequest and XML DOM for JavaScript Basics
First, we need to set up a few ground rules. The XMLHttpRequest object in particular, and XML DOM in general, is widely supported in any recent browser (IE, Mozilla, Safari, Opera) although, as usual, Microsoft has taken a slightly different tack on implementation and requires some special care. While our more progressive friends directly implement XMLHttpRequest, IE requires that you instantiate an ActiveXObject with the same properties. An excellent overview and full feature list is available at the Apple Developer Connection site.
A basic example follows:
var req;
function postXML(xmlDoc) {
if (window.XMLHttpRequest) req = new XMLHttpRequest();
else if (window.ActiveXObject) req = new ActiveXObject("Microsoft.XMLHTTP");
else return; // fall on our sword
req.open(method, serverURI);
req.setRequestHeader('content-type', 'text/xml');
req.onreadystatechange = xmlPosted;
req.send(xmlDoc);
}
function xmlPosted() {
if (req.readyState != 4) return;
if (req.status == 200) {
var result = req.responseXML;
} else {
// fall on our sword
}
}
The potential uses for this powerful tool are vast, and exploration of the possibilities has just begun. But before anyone gets carried away with trying to create an XML circus on the web, I suggest we set up a safety net to keep any high-flyers from breaking their necks.
JavaScript Error Handling Basics
JavaScript has come a long way since its earlier versions, which were crude, lacking in features, and just poorly implemented. Newer browsers not only support the try/catch/finally keywords you will recognize from C++ and Java, they also implement an onerror event that can trap any error conditions that arise during runtime. Usage is pretty straightforward:
function riskyBusiness() {
try {
riskyOperation1();
riskyOperation2();
} catch (e) {
// e is an object of type Error with
// at least two properties: name and message
} finally {
// clean up our mess
}
}
window.onerror = handleError; // safety net to trap all errors
function handleError(message, URI, line) {
// alert the user that this page may not respond properly
return true; // this will stop the default message
}
0 Comments:
Post a Comment
<< Home