自己寫一個json檔案,實現ajax
阿新 • • 發佈:2019-02-15
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> <style type="text/css"> .item-box li { width: 300px; height: 400px; border: 1px solid red; padding: 10px; overflow: hidden; float: left; margin: 0 20px 20px 0; text-align: center; } .item-img { width: 250px; height: 250px; } a:link { text-decoration: none; } </style> </head> <body> <ul class="item-box"> </ul> </body> </html> <script src="../jquery-1.9.1.min.js" type="text/javascript" charset="utf-8"></script> <script type="text/javascript"> $(function() { //獲取當前URL地址、隱藏資源真實地址,解決圖片引入問題 function pathUrl() { var strUrl = window.location.href, arrUrl = strUrl.split("/"); arrUrl.pop(); return arrUrl.concat('').join('/'); } //取得當前地址 var path = pathUrl(); console.log(path) //請求成功的回撥函式 function callBack(data) { var data = data.re var str = ""; $.each(data, function(index, item) { str += `<li> <a href=${"details.html?did="+item.id}> <img class="item-img" src=${path+item.src} /> <div class="item-content"> <h3 class="item-title">${item.title}</h3> <p class="item-subtitle"> <span class="item-time">${item.time}</span> </p> </div> </a> </li>`; }); $('.item-box').html(str); }; //傳送請求 $.ajax({ type: "get", url: "data.json", dataType: "json", success: callBack }); }); </script>
url的地址是一個data.json資料夾,下面是自己寫的假資料,還可以放圖片
{ "re": [ { "id":"0", "title": "50城買地1.2萬億元 一線城市地價全線降低", "src": "../img/1.jpg", "time": "2015-03-17" }, { "id":"1", "title": "50城買地1.2萬億元 一線城市地價全線降低", "src": "../img/2.jpg", "time": "2007-06-17" }, { "id":"2", "title": "50城買地1.2萬億元 一線城市地價全線降低", "src": "../img/3.jpg", "time": "2017-07-17" }, { "id":"3", "title": "50城買地1.2萬億元 一線城市地價全線降低", "src": "../img/4.jpg", "time": "2020-03-17" }, { "id":"4", "title": "50城買地1.2萬億元 一線城市地價全線降低", "src": "../img/5.jpg", "time": "2022-03-17" } ] }