Ajax獲取 Json文件提取數據javascript
1-1-1 json文件內容(item.json)css
[ { "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數據html
<!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 運行效果:java
1.3.1 文件結構jquery