2012-07-12 48 views
2

我正在使用JavaScript/jQuery試圖解析通過AJAX Get請求獲取的XML文檔。我無法發佈XML文檔,但它格式良好,並且我正在查找的標籤存在。 AJAX請求成功並返回Chrome和Firefox中的完整XML文檔 - 現在我無法解析它,出於某種原因。該代碼在Chrome中工作,但不支持Firefox或IE。我現在對IE沒有真正的興趣,但是我爲什麼沒有在Firefox中工作而迷失了方向。在Firefox中使用jQuery解析XML的問題

的JavaScript:

window.onload = function getGroupSets() { 
$.ajax({ 
    type: "GET", 
    dataType: "application/xml", 
    url: '../api/indicatorGroupSets.xml', 
    success: function(xml) { 

     /*Find Indicator Group Set tags in XML file */ 

     alert($(xml).find('indicatorGroupSet').length); 
     //This alert reads '0' in Firefox, '4' in Chrome 
     //The following function is not executed in Firefox: 

     $(xml).find('indicatorGroupSet').each(function() { 

      /*For each Set, get the name & ID*/ 

      var groupSet = { 
       name: $(this).attr('name'), 
       id: $(this).attr('id') 
      }; 
      alert(groupSet.name); 
      //Nothing displays here 
     }); 
    }, 
    error: function(jqXHR, textStatus, errorThrown) { 

     /*If an error occurs, alert the issue and a message to users */ 

     alert(jqXHR + ':' + textStatus + ':' + errorThrown + '\nThere has been an error, please refresh the page or contact the site administrator if the problem persists.'); 
    } 
}); 
} 

我一直在尋找了大半天的解決方案,但一切似乎是關於如何解析器沒有在IE工作,沒有太多關於這個問題的Firefox瀏覽器。

我很欣賞任何輸入!

+0

在一些例子中,我有很多問題,jQuery不能處理XML文檔中的命名空間。我只是轉向使用原生JavaScript,這很好。 – Sirko 2012-07-12 08:32:40

回答

0

嘗試告訴jQuery,您正在加載HTML。我的經驗是jQuery無法在Firefox中遍歷XML。一些未知的特定條件可能會引發這種行爲。

$.get("example.xml", function(data) { 
    .... 
}, "html"); 

有必要使用localName屬性,如果文檔中包含的命名空間來遍歷文件:

if (this.localName === "c:tagname") { 
    .... 
} 

這是可能使用jQuery的正常功能,瀏覽文件,如果它不包含命名空間:

if ($(this).is("tagname")) { 
    .... 
} 

遠離漂亮,但能夠完成任務。至少在Firefox中。 :)

+0

localname屬性?我在FF中遇到了同樣的問題,xml讀取工作在chrome中,但不是在FF中 – anam 2013-07-08 08:54:11