创建兼容浏览器的异步对象
ie6后使用了ActiveObject统一使用了Msxml2.XMLHttp,之前的版本使用的是Microsoft.XMLHttp
ie7之后和firefox都是支持XMLHttpRequest对象的。
可以这么写
var xmlHttp = false; function createXMLHttpRequest(){ try{ xmlHttp = new ActiveXObject("Msxml2.XMLHttp"); } catch(e){ try{ xmlHttp = new ActiveXObject("Microsoft.XMLHttp"); } catch(e){ xmlHttp = false; } } if (!xmlHttp && typeof XMLHttpRequest!= 'undefined'){ xmlHttp = new XMLHttpRequest(); } }
在Ajax基础教程中提供了一种建立方式。
var xmlHttp; function createXMLHttpRequest(){ if (window.ActiveXObject){ xmlHttp = new ActiveXObject("Microsoft.XMLHttp"); } else if (window.XMLHttpRequest){ xmlHttp = new XMLHttpRequest(); } }
使用版本二的ActionXObject会效率更高。修改为:
if (window.ActiveXObject){ (xmlHttp = new ActiveXObject("Msxml2.XMLHttp"))||(xmlHttp = new ActiveXObject("Microsoft.XMLHttp")); } else if (window.XMLHttpRequest){ xmlHttp = new XMLHttpRequest(); }