一个无懈可击的实例化XMLHttpRequest的方法

由于IE新旧版本以及与其他浏览器在ajax技术上的不同,往往需要对不同的浏览器做不同的处理,除了笨拙的浏览器嗅探技术,大约也就是对象检测技术可用了。

 

 function getHTTPRequest()
 {
    var xhr = false;
    if (window.XMLHttpRequest)
        xhr = new XMLHttpRequest(); //IE除外的浏览器
    else if (window.ActiveXObject)
    {
        try 
	    {
            xhr = new ActiveXObject("Msxm12.XMLHTTP");//最新版的ActiveX对象
        }
        catch(e) 
		{
            try 
			{
                xhr = new ActiveXObject("Microsoft.XMLHTTP");
            }
            catch(e) 
			{ 
				xhr = false;
			}			  
		}
    }
 }

接下来是一个应用的实例:

//完整的GET请求
var request = getHTTPRequest();
if(request)
{
	request.onreadystatechange = dosomething;
	request.open("GET","file.doc",true);
	request.send(null);
}
posted @ 2010-10-12 15:55  知识碎片  阅读(744)  评论(0编辑  收藏  举报