IE和FireFox下通用的js操作xml代码

本文介绍了一种使用JavaScript实现的XMLHttpRequest请求处理方法,通过自定义的varXmlReader对象进行GET请求,并根据不同浏览器环境选择合适的请求方式(IE或Gecko)。文章详细解释了如何加载URL、处理响应XML文档及如何使用XPath进行节点选择。
<script>
var XmlReader = function(){
this.GetHttpRequest = function(){
if (window.XMLHttpRequest) // Gecko
return new XMLHttpRequest();
else if (window.ActiveXObject) // IE
return new ActiveXObject("MsXml2.XmlHttp") ;
}
this.LoadUrl = function(urlToCall, asyncFunctionPointer){
var oXmlReader = this;
var bAsync = (typeof(asyncFunctionPointer) == "function");

var oXmlHttp = this.GetHttpRequest();
oXmlHttp.open("GET", urlToCall, bAsync);
if (bAsync){
oXmlHttp.onreadystatechange = function()
{
if (oXmlHttp.readyState == 4){
oXmlReader.DOMDocument = oXmlHttp.responseXML;
if (oXmlHttp.status == 200)
asyncFunctionPointer( oXmlReader ) ;
else
alert("XML request error: " + oXmlHttp.statusText + " (" + oXmlHttp.status + ")" ) ;
}
}
}

oXmlHttp.send(null) ;

if (!bAsync)
{
if (oXmlHttp.status == 200)
this.DOMDocument = oXmlHttp.responseXML ;
else
{
alert("XML request error: " + oXmlHttp.statusText + " (" + oXmlHttp.status + ")") ;
}
}
}
this.SelectNodes = function(xpath){
if (document.all) // IE
return this.DOMDocument.selectNodes(xpath) ;
else{ // Gecko
var aNodeArray = new Array();

var xPathResult = this.DOMDocument.evaluate(xpath, this.DOMDocument, this.DOMDocument.createNSResolver(this.DOMDocument.documentElement), XPathResult.ORDERED_NODE_ITERATOR_TYPE, null) ;
if (xPathResult){
var oNode = xPathResult.iterateNext() ;
while(oNode){
aNodeArray[aNodeArray.length] = oNode ;
oNode = xPathResult.iterateNext();
}
}
return aNodeArray ;
}
}
this.SelectSingleNode = function(xpath){
if (document.all) // IE
return this.DOMDocument.selectSingleNode( xpath ) ;
else{ // Gecko
var xPathResult = this.DOMDocument.evaluate( xpath, this.DOMDocument,
this.DOMDocument.createNSResolver(this.DOMDocument.documentElement), 9, null);

if (xPathResult && xPathResult.singleNodeValue)
return xPathResult.singleNodeValue ;
else
return null ;
}
}
}

</script>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值