DIV CSS 佈局教程網

您现在的位置: DIV+CSS佈局教程網 >> 網頁腳本 >  >> JavaScript入門知識 >> AJAX入門 >> AJAX詳解
讓 Firefox 也能用 selectNodes:跨瀏覽器讀取 XML 節點的實作
編輯:AJAX詳解     

最近在改專案裡用到 Ajax 的頁面,發現不少寫法在 Firefox 下直接失效。原因很單純:當年代碼只在 IE 測過就上線了,而兩邊的 XML 處理模型差異不小。

最典型的問題是讀取節點內容時,IE 可以直接用 selectNodes 與 selectSingleNode,而 Firefox 並沒有這兩個方法。找了好幾天,網路上提供的方案不是根本不能用,就是寫法繁瑣不便,最後我整理出一份可以直接引用的 JS 檔,讓 Firefox 也能用與 IE 一致的寫法。

讀取節點文字內容

IE 用 obj.text,Mozilla 系則要往 childNodes[0].nodeValue 取,因此先做一層判斷:

var GetNodeValue = function(obj)
{
  var str = "";
  if(window.ActiveXObject) // IE
  {
    str = obj.text;
  }
  else // Mozilla
  {
    try
    {
      str = obj.childNodes[0].nodeValue;
    }
    catch(ex)
    {
      str = "";
    }
  }
  return str;
}

為 XMLDocument 與 Element 動態擴充方法

接著用 prototype 擴充,把 IE 的 API 補回來。核心是利用 document.implementation.hasFeature("XPath", "3.0") 判斷 XPath 是否可用,可用時才掛上 selectNodes / selectSingleNode;同時也補上 loadXML,讓 Firefox 能直接從字串載入 XML。

if(document.implementation && document.implementation.createDocument)
{
  XMLDocument.prototype.loadXML = function(XMLString)
  {
    var childNodes = this.childNodes;
    for (var i = childNodes.length - 1; i >= 0; i--)
      this.removeChild(childNodes[i]);

    var dp = new DOMParser();
    var newDOM = dp.parseFromString(XMLString, "text/XML");
    var newElt = this.importNode(newDOM.documentElement, true);
    this.appendChild(newElt);
  };

  if( document.implementation.hasFeature("XPath", "3.0") )
  {
    XMLDocument.prototype.selectNodes = function(cXPathString, xNode)
    {
      if( !xNode ) { xNode = this; }
      var oNSResolver = this.createNSResolver(this.documentElement);
      var aItems = this.evaluate(cXPathString, xNode, oNSResolver,
              XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
      var aResult = [];
      for( var i = 0; i < aItems.snapshotLength; i++)
      {
        aResult[i] = aItems.snapshotItem(i);
      }
      return aResult;
    }

    Element.prototype.selectNodes = function(cXPathString)
    {
      if(this.ownerDocument.selectNodes)
      {
        return this.ownerDocument.selectNodes(cXPathString, this);
      }
      else{throw "For XML Elements Only";}
    }
  }

  if( document.implementation.hasFeature("XPath", "3.0") )
  {
    XMLDocument.prototype.selectSingleNode = function(cXPathString, xNode)
    {
      if( !xNode ) { xNode = this; }
      var xItems = this.selectNodes(cXPathString, xNode);
      if( xItems.length > 0 )
      {
        return xItems[0];
      }
      else
      {
        return null;
      }
    }

    Element.prototype.selectSingleNode = function(cXPathString)
    {
      if(this.ownerDocument.selectSingleNode)
      {
        return this.ownerDocument.selectSingleNode(cXPathString, this);
      }
      else{throw "For XML Elements Only";}
    }
  }
}

把這段存成 JS 檔並在頁面中引用,XML 節點的讀取寫法就能與 IE 保持一致,已實測可用。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved