XMLHttpRequest对象如何兼容各浏览器使用?

时间:2022-04-29
本文章向大家介绍XMLHttpRequest对象如何兼容各浏览器使用?,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

什么是 XMLHttpRequest 对象? XMLHttpRequest 对象用于在后台与服务器交换数据。 XMLHttpRequest 对象是开发者的梦想,因为您能够: 在不重新加载页面的情况下更新网页 在页面已加载后从服务器请求数据 在页面已加载后从服务器接收数据 在后台向服务器发送数据 所有现代的浏览器都支持 XMLHttpRequest 对象。

1、如何创建兼容良好的XMLHttpRequest 对象:

function createXmlRequest(){ 
    var xmlHttp;
	try{ 
        xmlHttp=new ActiveXObject("Msxml2.XMLHTTP"); 
    }catch(e){ 
        xmlHttp=new ActiveXObjec("Microsoft.XMLHTTP"); // 老版本的 Internet Explorer (IE5 和 IE6)
    }if(!xmlHttp && typeof XMLHttpRequest!='undefined'){ 
        try{ 
            xmlHttp=new XMLHttpRequest(); 
        }catch(e){ 
            xmlHttp=false; 
        } 
    }
    return xmlHttp;
}

2、如何使用?以Struts为例:

var xhr = createXmlRequest();
var url = "checkImsiJt.do?startid="+startid+"&endid="+endid;
xhr.open("GET",url,true);
xhr.onreadystatechange = function(){
    if (xhr.readyState == 4 && xhr.status == 200) {
        var msg = xhr.responseText;
        // TOOD 响应后台输出结果
    }
};
xhr.send(null);

 Struts的处理请求:

// 后台输出:
String result = "xxxx";
response.setContentType("text/html;charset=GBK");
response.getWriter().write(result);