自己写一个json文件,实现ajax

<!DOCTYPE html>
<html>

	<head>
		<meta charset="UTF-8">
		<title></title>
		<style type="text/css">
			.item-box li {
				width: 300px;
				height: 400px;
				border: 1px solid red;
				padding: 10px;
				overflow: hidden;
				float: left;
				margin: 0 20px 20px 0;
				text-align: center;
			}
			
			.item-img {
				width: 250px;
				height: 250px;
			}
			
			a:link {
				text-decoration: none;
			}
		</style>
	</head>

	<body>
		<ul class="item-box">
		</ul>
	</body>

</html>
<script src="../jquery-1.9.1.min.js" type="text/javascript" charset="utf-8"></script>
<script type="text/javascript">
	$(function() {
		//获取当前URL地址、隐藏资源真实地址,解决图片引入问题
		function pathUrl() {
			var strUrl = window.location.href,
				arrUrl = strUrl.split("/");
			arrUrl.pop();
			return arrUrl.concat('').join('/');
		}
		//取得当前地址
		var path = pathUrl();
		console.log(path)
		//请求成功的回调函数
		function callBack(data) {
			var data = data.re
			var str = "";
			$.each(data, function(index, item) {
				str += `<li>
                            <a href=${"details.html?did="+item.id}>
                            <img class="item-img" src=${path+item.src} />
                            <div class="item-content">
                                <h3 class="item-title">${item.title}</h3>
                                <p class="item-subtitle">
                    <span class="item-time">${item.time}</span>
                   </p>
                            </div>
                            </a>
                        </li>`;
			});
			$('.item-box').html(str);
		};
		//发送请求
		$.ajax({
			type: "get",
			url: "data.json",
			dataType: "json",
			success: callBack
		});

	});
</script>

url的地址是一个data.json文件夹,下面是自己写的假数据,还可以放图片

{
    "re": [
        {
            "id":"0",
            "title": "50城买地1.2万亿元 一线城市地价全线降低",
            "src": "../img/1.jpg",
            "time": "2015-03-17"
        },
        {
            "id":"1",
            "title": "50城买地1.2万亿元 一线城市地价全线降低",
            "src": "../img/2.jpg",
            "time": "2007-06-17"
        },
        {
            "id":"2",
            "title": "50城买地1.2万亿元 一线城市地价全线降低",
           "src": "../img/3.jpg",
            "time": "2017-07-17"
        },
        {
            "id":"3",
            "title": "50城买地1.2万亿元 一线城市地价全线降低",
            "src": "../img/4.jpg",
            "time": "2020-03-17"
        },
        {
            "id":"4",
            "title": "50城买地1.2万亿元 一线城市地价全线降低",
           "src": "../img/5.jpg",
            "time": "2022-03-17"
        }
    ]
}

猜你喜欢

转载自blog.csdn.net/m_ssy/article/details/80505441