Ajax讀取XML實現動態下拉導航
2024-09-01 08:29:47
供稿:網友
根據客戶的需要做一個產品的分類的導航菜單,以前使用ASP遞歸讀取的。速度慢,而且消耗大量服務器資源。干脆改成AJAX+XML。共享出來和大家交流。希望各位能幫忙改進。
產品分類的XML文件
代碼如下:
//id為自身id,pid為父級分類ID
<?xml version="1.0" encoding="UTF-8" ?>
<Proot>
<Item id="1" pid="0">1321系列</Item>
<Item id="2" pid="1">43223系列</Item>
</Proot>
js代碼
代碼如下:
var root;
//FireFox不支持selectNodes方法,在網上找到這段代碼解決了這個問題。兼容了IE和FireFox.
//創建selectNodes方法
if( document.implementation.hasFeature("XPath", "3.0") )
{
// prototying the XMLDocument
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;
}
// prototying the Element
Element.prototype.selectNodes = function(cXPathString)
{
if(this.ownerDocument.selectNodes)
{
return this.ownerDocument.selectNodes(cXPathString, this);
}
else{throw "For XML Elements Only";}
}
}
function createXMLHttpRequest() {
if (window.ActiveXObject) {
oXmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
else if (window.XMLHttpRequest) {