最近看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;
}
新闻热点
疑难解答
图片精选