JSONP配合jQuery Templates:從台北市公開政府資料平臺取資料

  • 4944
  • 0

JSONP配合jQuery Templates:從台北市公開政府資料平臺取資料

Dotblogs 的標籤: , , ,

想要練習 JSONP 加上 jQuery Templates 的實務應用,正好有個很棒的資料來源:台北市公開政府資料平臺,所以就做了這個練習。

這個練習中,包含利用正規式,把資料來源的「內容」值之電話號碼過濾出來,然後也利用 jQuery 做偶數列背景顏色呈現。

Using_JSONP_GetODGI_Swimming_Pool.htm

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.7.1.min.js"></script>
    <script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jquery.templates/beta1/jquery.tmpl.min.js"></script>
    <link href="css/common.css" type="text/css" rel="stylesheet" />
    <script type="text/x-jquery-tmpl" id="tmplItem">
        <tr><td>${countRow()}</td><td>${標題}</td><td>${getPhone(內容)}</td><td>${顯示用地址}</td><td>${內容}</td></tr>
    </script>
    <script type="text/javascript">
        $(function () {
            $("#btnGetODGI").click(btnGetODGI_Click);
        });

        function btnGetODGI_Click() {
            var sUrl = "http://taipeicityopendata.cloudapp.net/v1/TaipeiOGDI/okswim/?format=json";
            $.getJSON(sUrl + '&callback=?', jsonp_callback);
        }

        function jsonp_callback(data) {
            $("#tmplItem").tmpl(data.d).appendTo("#tb");
            $('#tb tr:odd').addClass('odd');
        }

        function getPhone(str) {
            var regPhone = /\d{3,10}[-\d{3,4}]*/;
            var result = str.match(regPhone);
            return (result === null) ? "" : result;
        }

        var rowNum = 0;
        function countRow() {
            rowNum++;
            return rowNum;
        }
    </script>
</head>
<body>
    <input id="btnGetODGI" type="button" value="取得ODGI-游泳池資料" />
    <table class="myTable" border="1" id="tblList">
        <thead>
            <th>項次</th>
            <th>名稱</th>
            <th>連絡電話</th>
            <th>地址</th>
            <th>內容</th>
        </thead>
        <tbody id="tb">
        </tbody>
    </table>
</body>
</html>

common.css

.myTable
{
    border: gray 1px solid;
    width: 95%;
    background-color: white;
    font-size: 12pt;
    font-family: VERDANA;
    border-collapse: collapse;
}
.myTable th
{
    background-color: #9999FF;
    border: 1px dotted gray;
    color: black;
    font-weight: normal;
    text-align: left;
}
.myTable td
{
    text-align: left;
    border: 1px dotted gray;
}
.odd
{
    text-align: left;
    border: 1px dotted gray;
    background-color: lightYellow;
}

最後呈現結果:

--------
沒什麼特別的~
不過是一些筆記而已