ie无法使用jquery解析xml的解决方法

功能描述:使用jQuery解析已经定义好内容的xml文件

1.xml文件:menu.xml

<?xml version="1.0" encoding="gb2312"?>
<menus>
    <menu>
        <id>1</id>
        <name>system</name>
        <parentId>0</parentId>
        <target>mainFrame</target>
        <url></url>
    </menu>
    <menu>
        <id>2</id>
        <name>company</name>
        <parentId>1</parentId>
        <target>mainFrame</target>
        <url></url>
    </menu>
</menus>

2.自定义js文件解析xml文件:index.js

$(document).ready(function(){
    $.ajax({
           url:"xml/menu.xml ",
           type:"POST", 
           dataType:"xml",
           success:function(data){
                      $(data).find("menu").each(function(){
                               alert("success");
                               alert($(this).text());
                      });
           },
           error:function(data){
                     alert("fail:");
           }
    });
});

3.新建index.html文件引入jQuery.js、xml文件及index.js文件,在ie中(任何版本)运行index.html,结果总是弹出“fail”,但是在Firefox中的结果却是“success”。

在网上搜了很多资料,最后在这篇文章http://www.newmediafun.com/2009/07/ 标题:parsing-xml-with-jquery-in-internet-explorer上找到了解决方案。是因为ie中的限制无法正确解析xml文件,它解析出的是一个text对象(在我引用的文章中有更详细的解释)所以针对这个加入判断就可以解决了

正确代码index.js

$(document).ready(function(){
    $.ajax({
         url:"xml/menu.xml",
         type:"POST", 
         dataType:($.browser.msie) ? "text" : "xml",
         success:function(data){
                var xml;
                if( typeof data == "string" ){
                         xml = new ActiveXObject("Microsoft.XMLDOM");
                         xml.async = false;
                         xml.loadXML(data);
                } else {
                         xml = data; 
                }
              $(xml).find("menu").each(function(){
 
                  alert("success");
                  alert($(this).text());
              });
        },
       error:function(data){
               alert("fail:");
       }
    });
});

原文地址: http://www.yzswyl.cn/blread-840.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值