Ajax学习系列——创建XMLHttpRequest对象

Ajax - 创建XMLHttpRequest对象

首先介绍什么是XMLHttpRequest:

XMLHttpRequest是Ajax的基础。中文可以解释为可扩展超文本传输请求。术语缩写为XHR。

XMLHttpRequest对象可以在不同服务器提交整个页面的情况下,实现局部刷新。

创建XMLHttpRequest对象:

现阶段主流浏览器(IE7+,Firefox,Google Chrome,Safari)等均存在XMLHttpRequest对象,可以直接创建,语法如下:

var xhr = new XMLHttpRequest();

老版本的IE浏览器(IE5和IE6)使用的是ActiveX对象:

var xhr = new ActiveXObject("Microsoft.XMLHTTP");

所以在创建XMLHttpRequest对象时,我们需要检查浏览器是否只是XMLHttpRequest对象(虽然现在IE5和IE6基本没人用,但是还是要有的)。具体方法如下:

var xmlhttp = null; 
if (window.XMLHttpRequest) {
    xmlhttp = new XMLHttpRequest(); 
} else{
    xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); 
}

另外下面这种方法也可以:

var xhr = null;
if(typeof(XMLHttpRequest) != undefined){
    xhr = new XMLHttpRequest();
}else{
    xhr = new ActiveXObject("Microsoft.XMLHttp");
}

猜你喜欢

转载自www.cnblogs.com/guo-xu/p/10498528.html