The core of the AJAX framework component is the XMLHttpRequest JavaScript object, which allows the client developer to send and receive XML documents over HTTP without disrupting user action and without exploiting hidden pages. Now, some people may feel fear because it suddenly allows client developers who are likely to use validated forms and animated images too much to pass XML documents and process HTTP header information, but without risk there is no gain. We don't have to be afraid, I'll demonstrate how to use XMLHttpRequest to add some previously impossible, unworkable features that also reduce errors and improve product quality.
XMLHttpRequest and XML DOM in JavaScript
First, we need to establish some rules. Special XMLHttpRequest Objects and general XML DOM are widely supported by the latest browsers (IE, Mozilla, Safari, Opera), although in general, Microsoft has a slight increase in its implementation and requires some special processing. Even though more of our friends have directly implemented XMLHttpRequest, IE asks you to instantiate a activexobject with the same attributes. An overview and a list of all the features can be found on the Apple developer relationship site. The following is a basic example:
var req;
function postXML(xmlDoc) {
if (window.XMLHttpRequest) req = new XMLHttpRequest();
else if (window.ActiveXObject) req = new ActiveXObject("Microsoft.XMLHTTP");
else return; // 失败了
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 {
// 失败了
}
}
There are many potential users of this powerful feature, and the search for what it might do is just beginning. But before you try to build XML functionality on the Web, I suggest you set up a "safety net" to keep your ambitions (ideas) from being hit.
JavaScript Error Handling Basics
JavaScript has been there for a long time, and its earlier versions are primitive, lacking features, just implemented. The latest browsers not only support the Try/catch/finally keyword in C + + and Java, but also implement the OnError event, which can capture any errors that occur at run time. The use of it is very straightforward:
function riskyBusiness() {
try {
riskyOperation1();
riskyOperation2();
} catch (e) {
// e是一个Error类型的对象,至少有两个属性:name和message
} finally {
// 清除消息
}
}
window.onerror = handleError; // 捕捉所有错误的安全网
function handleError(message, URI, line) {
// 提示用户这个页面可能无法正常响应
return true; // 停止默认的消息
}