通过ajax请求数据后,进行页面渲染。
文件介绍
1.goods.json,用于模拟后台接口数据
[ { "price":"1000", "name":"小米手机", "imgUrl":"img/1.png" }, { "price":"2000", "name":"华为手机", "imgUrl":"img/1.png" }, { "price":"3000", "name":"锤子手机", "imgUrl":"img/1.png" }, { "price":"2899", "name":"一加手机", "imgUrl":"img/1.png" }, { "price":"1099", "name":"魅族手机", "imgUrl":"img/1.png" } ]
2.html,用于显示页面内容。
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>ajax请求数据并渲染到页面</title> <style type="text/css"> .inner { display: inline-block; padding: 20px; border: 1px solid gainsboro; text-align: center; margin-left: 20px; } .inner img { width: 200px; height: 200px; font-size: 0; } h3, span { font-size: 20px; } </style> </head> <body> <div id="test"> <!--假数据--> <!--<div class="inner"> <img src="img/1.png"/> <h3>名称:小米手机</h3> <span>价格:1000</span> </div>--> </div> </body> </html> <script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script> <script type="text/javascript"> $(function() { $.ajax({ type: "GET", url: "goods.json", dataType: "json", success: function(data) { var str = ''; $.each(data, function(i, n) { str += '<div class="inner">'; str += '<img src="' + n.imgUrl + '"/>'; str += '<h3>' + '名称:' + n.name + '</h3>'; str += '<span>' + '价格:¥' + n.price + '</span>'; str += '</div>'; }); $("#test").append(str); } }); }); </script>
3.注意事项
该实例中仅仅有index.html文件,goods.json文件,和一张图片,其中ajax中的url指定json文件的路径(不能写错)。
4.效果如下