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

 

相关文章:

  • 2021-10-10
  • 2022-01-05
  • 2021-10-16
  • 2022-12-23
  • 2021-09-11
  • 2021-09-12
  • 2022-03-03
  • 2022-12-23
猜你喜欢
  • 2021-10-05
  • 2021-08-27
  • 2021-09-16
  • 2021-10-28
  • 2022-12-23
相关资源
相似解决方案