微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

学习笔记之利用ajax请求xml文件,解析其中内容

之前一直困扰在如何用js解析xml文件,从网上也找了好多方法代码很多,自己也理不清楚,终于有大神帮助,教我用ajax来读取和解析xml,感觉收获颇多,直接上代码

function ajaxRequest() {

	$.ajax({
	type : 'GET',url : "static/download/data/data.xml",success : function(xml) {
		var strleft = '<dt>下载分类</dt>';
		var j = 1;
		$(xml).find("item").each(function() {	//遍历第一层		
			var itemname = $(this).attr("name");
			var subitem = "";			
			$(this).children("download").each(function() {    //遍历第二层
				subitem += '<li class="downitem"><a title="点击下载" href="';
				subitem +=$(this).attr("url");
				subitem +='">';
				subitem += $(this).attr("name");
				subitem += '</a></li>';
			});
			var num=$(this).children("download").length;
			strleft += '<dd ><a href="#" onclick="item_method('+ j + ','+num+')">';
			strleft += itemname;
			strleft += '</a></dd>';
			
			$("#item" + j).html(subitem);
			if (j != 1) {
				$("#item" + j).hide();
			}
			j += 1;

		});
		$("#leftmenu").html(strleft);
	},error : function() {
	}
});
}
上面的方法就是解析xml的方法了,在初始js里调用即可
$(document).ready(function() {

	ajaxRequest();

});

再把xml一起附上,以便参考
<?xml version="1.0" encoding="utf-8" ?>
<items>
	<item name="案例下载">
		<download name="案例1" url="http://36.21.0.1:8080/nav/index.html"></download>
		<download name="案例2" url="http://36.21.0.1:8080/map/index.html"></download>
		<download name="案例3" url="http://36.21.0.1:8080/cqexchange/"></download>
	</item>
	<item name="类库下载">
		<download name="类库1" url="http://36.21.0.1:8080/nav/index.html"></download>
		<download name="类库2" url="http://36.21.0.1:8080/map/index.html"></download>
		<download name="类库3" url="http://36.21.0.1:8080/cqexchange/"></download>
		<download name="类库4" url="http://36.21.0.1:8080/cqexchange/datapublish.html"></download>
		<download name="类库5" url="http://36.21.0.1:8080/devcenter/"></download>
		<download name="类库6" url="http://36.21.0.1:8080/devcenter/"></download>
	</item>
	<item name="说明文档下载">
		<download name="文档1" url="http://36.21.0.1:8080/nav/index.html"></download>
		<download name="文档2" url="http://36.21.0.1:8080/map/index.html"></download>
		<download name="文档3" url="http://36.21.0.1:8080/cqexchange/"></download>
		<download name="文档4" url="http://36.21.0.1:8080/cqexchange/datapublish.html"></download>
		<download name="文档5" url="http://36.21.0.1:8080/devcenter/"></download>
	</item>
	<item name="其他下载">
		<download name="其他1" url="http://36.21.0.1:8080/nav/index.html"></download>
		<download name="其他2" url="http://36.21.0.1:8080/map/index.html"></download>
		</item>
</items>

原文地址:https://www.jb51.cc/ajax/162648.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐