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回调中。