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;
iftypeof 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:");
       }
    });
});
原文地址:https://www.cnblogs.com/timy/p/1806378.html