AJAX Hacks 之HACK1. 檢測瀏覽器的相容性

來源:互聯網
上載者:User
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函數是事件處理的核心。

<

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.