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

什么是 XMLHttpRequest 对象?

XMLHttpRequest 对象用于在后台与服务器交换数据。
XMLHttpRequest 对象是开发者的梦想,由于您可以:
在不从新加载页面的状况下更新网页
在页面已加载后从服务器请求数据
在页面已加载后从服务器接收数据
在后台向服务器发送数据
全部现代的浏览器都支持 XMLHttpRequest 对象。html


一、如何建立兼容良好的XMLHttpRequest 对象:java

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;
}


二、如何使用?以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);
相关文章
相关标签/搜索