通过ajax请求数据后,进行页面渲染。
文件介绍
1.goods.json,用于模拟后台接口数据
{
"cursor": 0,
"size": 40,
"page": 0,
"result": [{
"price": "1000",
"name": "小米手机",
"imgUrl": "img/1.png"
},
{
"price": "2000",
"name": "华为手机",
"imgUrl": "img/1.png"
},
{
"price": "3000",
"name": "锤子手机",
"imgUrl": "img/1.png"
},
{
"price": "4000",
"name": "一加手机",
"imgUrl": "img/1.png"
},
{
"price": "5000",
"name": "魅族手机",
"imgUrl": "img/1.png"
},
{
"price": "6000",
"name": "小米手机",
"imgUrl": "img/1.png"
},
{
"price": "7000",
"name": "华为手机",
"imgUrl": "img/1.png"
},
{
"price": "8000",
"name": "锤子手机",
"imgUrl": "img/1.png"
},
{
"price": "9899",
"name": "一加手机",
"imgUrl": "img/1.png"
},
{
"price": "10099",
"name": "魅族手机",
"imgUrl": "img/1.png"
},
{
"price": "20000",
"name": "小米手机",
"imgUrl": "img/1.png"
},
{
"price": "30000",
"name": "华为手机",
"imgUrl": "img/1.png"
},
{
"price": "40000",
"name": "锤子手机",
"imgUrl": "img/1.png"
},
{
"price": "50899",
"name": "一加手机",
"imgUrl": "img/1.png"
},
{
"price": "60099",
"name": "魅族手机",
"imgUrl": "img/1.png"
}
],
"hasnext": 100
}
2.html,用于显示页面内容。
ajax请求数据并渲染到页面#test{
width: 100%;
padding: 10px;
height: 1000px;
border: 1px solid gainsboro;
border-radius: 8px;
}
.inner {
display: inline-block;
padding: 20px;
border: 1px solid gainsboro;
text-align: center;
margin-left: 20px;
margin-bottom: 20px;
border-radius: 8px;
}
.inner:hover{
border: 1px solid deeppink;
}
.inner:hover h3{
color: deeppink;
}
.inner img {
width: 200px;
height: 200px;
font-size: 0;
}
h3,
span {
font-size: 20px;
}
$(function() {
$.ajax({
type: "GET",
url: "goods.json",
dataType: "json",
success: function(res) {
console.log(res);
console.log(typeof(res));
var data = res.result;
console.log(data);
var str = '';
// 注意:输出的i与obj分别为下标与单个的对象
$.each(data, function(i, obj) {
// console.log(i);
// console.log(obj);
str += '
str += '';
str += '
' + '名称:' + obj.name + '
';str += '' + '价格:¥' + obj.price + '';
str += '
});
$("#test").append(str);
}
});
});
3.注意事项
该实例中仅仅有index.html文件,goods.json文件,和一张图片,其中ajax中的url指定json文件的路径(不能写错)。
4.效果如下