最近看JavaScript高級程序設計,大有收獲,接下來幾天寫一下讀書筆記。之前寫了一篇Ajax初步理解的隨筆,里面有個函數用來創建XmlHttpRequest對象,瀏覽器兼容性原因,寫出的代碼通過大量if判斷或者try,catch語句將函數引導到正確代碼處。 
復制代碼 代碼如下:
 
<script type="text/javascript"> 
function createXHR(){ 
var xhr = null; 
try { 
// Firefox, Opera 8.0+, Safari,IE7+ 
xhr = new XMLHttpRequest(); 
} 
catch (e) { 
// Internet Explorer 
try { 
xhr = new ActiveXObject("Msxml2.XMLHTTP"); 
} 
catch (e) { 
try { 
xhr = new ActiveXObject("Microsoft.XMLHTTP"); 
} 
catch (e) { 
xhr = null; 
} 
} 
} 
return xhr; 
} 
</script> 
復制代碼 代碼如下:
 
function createXHR(){ 
var xhr=null; 
if(typeof XMLHttpRequest !='undefined'){ 
xhr = new XMLHttpRequest(); 
createXHR=function(){ 
return new XMLHttpRequest(); 
} 
}else{ 
try { 
xhr = new ActiveXObject("Msxml2.XMLHTTP"); 
createXHR=function(){ 
return new ActiveXObject("Msxml2.XMLHTTP"); 
} 
} 
catch (e) { 
try { 
xhr = new ActiveXObject("Microsoft.XMLHTTP"); 
createXHR=function(){ 
return new ActiveXObject("Microsoft.XMLHTTP"); 
} 
} 
catch (e) { 
createXHR=function(){ 
return null; 
} 
} 
} 
} 
return xhr; 
} 
新聞熱點
疑難解答
圖片精選