ajax|浏览器
AJAX Hacks 之HACK1. 检测浏览器的兼容性
本节介绍如何使用JavaScript 建立起IE或Mozilla浏览器相应的请求对象。客户端使用的浏览器是各种各样的。因此也有不同的请求对象。如在Firefox, Netscape, Safari,Opera中是XMLHttpRequest。IE则是Microsoft.XMLHTTP 或 Msxml2.XMLHTTP。
使用AJAX的第一步是检测客户浏览器的类型,根据相应的类型取得request 对象。下面就是取得该对象的完整代码:
/* Initialize a Request object that is already constructed /
function initReq(reqType,url,bool){
/ Specify the function that will handle the HTTP response */
request.onreadystatechange=handleResponse;
/* onreadystatechange监听handleResponse函数。接下来就是打开连接,发送请求……
*/
request.open(reqType,url,bool);
request.send(null);
}
/* Wrapper function for constructing a Request object.
Parameters:
reqType: The HTTP request type such as GET or POST.
url: The URL of the server program.
asynch: Whether to send the request asynchronously or not. */
function httpRequest(reqType,url,asynch){
//Mozilla-based browsers
if(window.XMLHttpRequest){ //如果是非IE浏览器
request = new XMLHttpRequest(); //取得对象。
initReq(reqType,url,asynch);
} else if (window.ActiveXObject){ //如果是IE浏览器
request=new ActiveXObject("Msxml2.XMLHTTP");
if (! request){
request=new ActiveXObject("Microsoft.XMLHTTP");
}
if(request){
initReq(reqType,url,asynch);
/* Unlikely to branch here, as IE users will be able to use either one of the
constructors*/
} else {
alert("Your browser does not permit the use "+
"of all of this application's features!");}
} else {
alert("Your browser does not permit the use "+
"of all of this application's features!");}
}
应当注意到handleResponse函数是事件处理的核心。
<