1. 程式人生 > >jquery動態載入並解析xml至ul

jquery動態載入並解析xml至ul

做前臺廣告模組,將廣告的資訊(網址,圖片路徑)存入xml便於修改

ad.xml:

<?xml version="1.0" encoding="UTF-8"?>
<ads>
	<ad>
		<href>http://www.meituan.com</href>
		<imgsrc>images/ad/meituan.jpg</imgsrc>
		<description>美團</description>
	</ad>
	<ad>
		<href>http://www.baidu.com</href>
		<imgsrc>images/ad/baidu.png</imgsrc>
		<description>百度</description>
	</ad>
	<ad>
		<href>http://www.youku.com</href>
		<imgsrc>images/ad/youku.jpg</imgsrc>
		<description>優酷</description>
	</ad>
	<ad>
		<href>http://www.tudou.com</href>
		<imgsrc>images/ad/yilong.jpg</imgsrc>
		<description>藝龍</description>
	</ad>
</ads>

注:不加http://會預設訪問工程內的網址

 

前臺html:

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8" />
		<title>測試</title>
	</head>
	<script src="js/jquery-1.4.4.min.js"></script>
	<script>
		$(document).ready(function(){
        	$.ajax({  
        	    url: 'ad.xml',
        	    type: 'GET',
        	    success: function(xml) {
        	    	$(xml).find("ad").each(function (){
        	    		var ad = $(this);
        	    		var imgsrc = ad.find("imgsrc").text();
        	    		var href = ad.find("href").text();
        	    		$("#ul1").append("<li><a href='"+href+"'><img alt='' src='"+imgsrc+"'/></a></li>");
        	    	});
        	    }
        	});
        });
		
	</script>
	<body>
		<h3>歡迎</h3>
		<ul id="ul1">
		</ul>
		<a href="http://www.baidu.com">百度</a>
	</body>
</html>

 

測試時發現Adblock Plus(瀏覽器廣告攔截外掛)會攔截資料,f12報錯net::ERR_BLOCKED_BY_CLIENT