標籤:需要 hang img javascrip microsoft alt ref 方法 tle
摘自
Ajax擷取 Json檔案提取資料
1. json檔案內容(item.json)
[ { "name":"張國立", "sex":"男", "email":"[email protected]", "url":"./img/1.jpg" }, { "name":"張鐵林", "sex":"男", "email":"[email protected]", "url":"./img/2.jpg" }, { "name":"鄧婕", "sex":"女", "email":"[email protected]", "url":"./img/3.jpg" }, { "name":"張國立", "sex":"男", "email":"[email protected]", "url":"./img/4.jpg" }, { "name":"張鐵林", "sex":"男", "email":"[email protected]", "url":"./img/5.jpg" }, { "name":"鄧婕", "sex":"女", "email":"[email protected]", "url":"./img/6.jpg" }]
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>
3.運行效果
4.檔案結構
Ajax擷取 Json檔案提取資料