Ajax获取 Json文件提取数据
Ajax获取 Json文件提取数据
1-1-1 json文件内容(item.json)
[ { "name":"张国立", "sex":"男", "email":"zhangguoli@123.com", "url":"./img/1.jpg" }, { "name":"张铁林", "sex":"男", "email":"zhangtieli@123.com", "url":"./img/2.jpg" }, { "name":"邓婕", "sex":"女", "email":"zhenjie@123.com", "url":"./img/3.jpg" }, { "name":"张国立", "sex":"男", "email":"zhangguoli@123.com", "url":"./img/4.jpg" }, { "name":"张铁林", "sex":"男", "email":"zhangtieli@123.com", "url":"./img/5.jpg" }, { "name":"邓婕", "sex":"女", "email":"zhenjie@123.com", "url":"./img/6.jpg" } ]
1-1-2 发送Ajax请求,获取Json数据
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Insert title here</title> <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0"> <script type="text/javascript" src="js/jquery-1.10.2.min.js"></script> <style type="text/css"> .p1{ font-size: 14px; color: #000; } .p2{ font-size: 12px; color: #b0b0b0; } .p3{ font-size: 14px; color: #ff5f19; } .product{ width:100%; position: relative; margin: 20px 0 5px 0; height: 100px; background: #fafafa; } .img{ width: 100px; height: 100px; float: left; margin-right: 20px; } .p{ display:inline-block; float:left; width:50%; margin-top:6px; font-family: Microsoft YaHei; } .p1{ margin-top:16px; } </style> <script> //页面加载 获取全部信息 $(function(){ $.ajax({ type: "POST",//请求方式 url: "item.json",//地址,就是json文件的请求路径 dataType: "json",//数据类型可以为 text xml json script jsonp
success: function(result){//返回的参数就是 action里面所有的有get和set方法的参数 addBox(result); } }); /*$.get("item.json",function(result){ //result数据添加到box容器中; addBox(result); });*/ }); function addBox(result){ //result是一个集合,所以需要先遍历 $.each(result,function(index,obj){ $("#box").append("<div class='product'>"+//获得图片地址 "<div><img class='img' src="+obj['url']+"/></div>"+ //获得名字 "<div class='p1 p'>"+obj['name']+"</div>"+ //获得性别 "<div class='p2 p'>"+obj['sex']+"</div>"+ //获得邮箱地址 "<div class='p3 p'>"+obj['email']+"</div>"+ "</div>"); }); } </script> </head> <body> <!-- 构建装一个容器 --> <div id="box"> </div> </body> </html>
1.2.1 运行效果:
1.3.1 文件结构