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

前端之家收集整理的这篇文章主要介绍了学习笔记之利用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.f2er.com/ajax/162648.html

猜你在找的Ajax相关文章