讓資料顯示在畫面上


現在來使用剛剛學到的Ajax與Open Data,來實作一些小範例吧!首先,先來看看以下這個範例。

森林步道的API,點開來看裡面有什麼資料,點開網頁的動作就是GET
http://data.coa.gov.tw/Service/OpenData/DataFileService.aspx?UnitId=102

該如何抓取資料,請看以下範例

javascript的部分

//森林步道的API
var forestUrl = "http://data.coa.gov.tw/Service/OpenData/DataFileService.aspx?UnitId=102";

$.ajax({
   type: "GET",
   dataType: "json",
   url: forestUrl ,
   success: function(response) {

      //response就是回傳回來的JSON資料
      console.log(response);

      //這邊看要怎麼使用回來的資料,我們寫一個renderForestList()來把資料顯示在畫面上
      renderForestList(response);

   }
});
//$.ajax也可以用更簡潔的方式寫
$.getJSON( forestUrl , function( response) {
   console.log(response);
   renderForestList(response);
});
function renderForestList(trails){

   var html="";

   trails.forEach(function(trail) {

      console.log(trail);//先把資料印出來看看
      var name = trail['name'];
      var level = trail['level'];

      html += '<div>'+level+' - '+name+'</div>';

   }, this);

   $("#forest-list").html(html);

}

html的部分

<div id="forest-list"></div>

results matching ""

    No results matching ""