javascript获取xml对象的方法(使用XMLHttpRequest)

javascript获取xml对象有几种方法,在网海中也有很多这方面的示例文章,这里我记录下整理后个人觉得很好的一种实现方法。

先建立一个xml文件:

<?xml version="1.0" encoding="gb2312"?>
<test>
    <name>name</name>
    <msn>ok@www.ok.cn</msn>
</test>


 

在同目录中建个html文件:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<title>test</title>
<script>
function getXMLHttpRequest(){
	var progId,
	progIds = ["MSXML2.XMLHTTP.6.0" , "MSXML2.XMLHTTP", "Microsoft.XMLHTTP"];
	if (!window.ActiveXObject) {
		return new XMLHttpRequest();
	}else {
		for (var i  = progIds.length - 1; i >= 0; i--){
			try {
				return new ActiveXObject(progId = progIds[i]);
			} catch (ex) {
				progId = null;
			}
		}
	}
}
function loadClass(src){
	try{
		var xmlHttp = getXMLHttpRequest();
		xmlHttp.open("GET", src, false);
		xmlHttp.send(null);
		var stus = xmlHttp.status;
		if (stus == 200 || stus == 0 || stus == 304){
			return xmlHttp.responseText;
		}
	}catch(ex){
		alert("error!");
	}
}
var e = loadClass("xml.xml") ;
alert(e);
</script>
</head>
<body>
</body>
</html>


 

测试了ie和火狐浏览器,效果不错。

如果用ajax通过url取,把xmlHttp.send(null);var stus = xmlHttp.status;if (stus == 200 || stus == 0 || stus == 304){return xmlHttp.responseText;}放到ajax回调中。

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值