创建兼容IE、火狐、chrome、oprea浏览器的xmlDom对象方法

本文发布于:2012-09-25,最后更新于:2012-09-27,如果内容失效请留言告知。

在IE和火狐下,可以直接创建xmlDom对象来载入xml文件,但是在chrome和opera等webkit内核的浏览器下,则只能通过xmlhttp方式进行获取。

在IE和火狐下,直接创建的xmlDom对象可以跨域访问xml文件。但xmlhttp为了安全性禁止跨域访问,当跨域访问时即会报错如下:

Uncaught Error: NETWORK_ERR: XMLHttpRequest Exception 101

以下是一段兼容主流浏览器的xmlDom对象获取方法,仅供参考讨论,具体示例可参见本站首页的英语句子插件的效果(原版pjblog英语句子插件不支持webkit内核浏览器)。

code: jscript;
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
//检测系统支持的XMLDom方式
function E_getControlPrefix() {
  var prefixes = ["MSXML2", "Microsoft", "MSXML", "MSXML3"];
  var o, o2;
  for (var i = 0; i < prefixes.length; i++) {
    try {
      // try to create the objects
      o = new ActiveXObject(prefixes<span style="text-decoration: line-through;"> + ".XmlHttp");
      o2 = new ActiveXObject(prefixes<span style="text-decoration: line-through;"> + ".XmlDom");
      return E_getControlPrefix.prefix = prefixes<span style="text-decoration: line-through;">;
    }
    catch (ex) {};
  }
}
//创建xmldom对象
function loadXmlFile(xmlFile) {
  var xmlDom = null;
  if (window.ActiveXObject) { //支持IE浏览器,可跨域
    xmlDom = new ActiveXObject(E_getControlPrefix() + ".XMLDOM");
    //xmlDom.loadXML(xmlFile);//如果用的是XML字符串
    xmlDom.load(xmlFile); //如果用的是xml文件。
  } else if (document.implementation && document.implementation.createDocument) { //支持火狐浏览器,可跨域
    xmlDom=document.implementation.createDocument("","",null);
    xmlDom.load(xmlFile);
  } else if (window.XMLHttpRequest){  //xmlhttp方式,支持火狐、chrome、oprea等浏览器,但不可跨域
    var xmlhttp = new window.XMLHttpRequest();
    xmlhttp.open("GET", xmlFile, false);
    xmlhttp.send(null);
    if (xmlhttp.status == 200) {
      xmlDom = xmlhttp.responseXML;
    }
  } else {
    xmlDom = null;
  }
  return xmlDom;
}</span></span></span>

注: 

由于xmlhttp方式不允许跨域,所以访问非本域名地址下的xml文件时即会报错。当在本地以无域名的方式访问本地xml文件,应该也是一样当做跨域处理,所以也会同样的报错如下:

Uncaught Error: NETWORK_ERR: XMLHttpRequest Exception 101

点赞 (0)
  1. fasfd说道:

    [quote=长春PBT]看不懂啊

  2. 帕金森治疗说道:

    都兼容吗? 博主!
    学习下!
    http://www.pjszl.cn

  3. 圆刀片说道:

    在IE和火狐下,直接创建的xmlDom对象可以跨域访问xml文件。但xmlhttp为了安全性禁止跨域访问,当跨域访问时即会报错。

  4. 黔域工作室说道:

    学习了,看来opera也终于主流了

  5. 林肆说道:

    依旧看不懂啊,咱就会一点HTML代码来着,嘿嘿~

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

Captcha Code