Google Code Prettify

2016年5月11日 星期三

jQuery: 處理 json 資料

十年前,傳資料偏好用 xml 格式,因為 xml 太複雜,不好閱讀,也增加傳輸的資料量,現在大部份會選擇用 JSON 格式。這裡整理一個簡單的 jQuery 處理 JSON 資料的方法。

先看一下結果:
  • 啟動: 畫面上只有兩個按鍵,在按了按鍵後會顯現出資料。
  • click【html】:顯現出 bumblerMa.html 的內容
  • click【json】: 抓取 president.json 的內容,組成 html 後顯示出來。
上面的執行結果是要顯示兩個檔案的內容 bumblerMa.html 及 president.json,先來看一下這兩個檔案的內容:
  • bumblerMa.html: 這個 html 檔並非完整包含 <html>、<body> 等 tag 的 html,因為這個檔的內容在底下的程式中,是被載入後鑲嵌於既有網頁中。
<H1>Ma the bumbler</H1>

<H3>A former heart-throb loses his shine</H3>
<DIV>Nov 17th 2012 | TAIPEI | From the print edition</DIV>
<br/>
WHEN he was first elected in 2008, Taiwan’s president, Ma Ying-jeou, offered Taiwanese high hopes that the island’s economy would open a new chapter. He promised ground-breaking agreements with China to help end Taiwan’s growing economic marginalisation. At the time, Mr Ma’s image was of a clean technocrat able to rise above the cronyism and infighting of his party, the Kuomintang (KMT). He was a welcome contrast to his fiery and pro-independence predecessor, Chen Shui-bian, now in jail for corruption.
<br/>
Five years on, and despite being handily re-elected ten months ago, much has changed. In particular, popular satisfaction with Mr Ma has plummeted, to a record low of 13%, according to the TVBS Poll Centre. The country appears to agree on one thing: Mr Ma is an ineffectual bumbler.
<br/>
  • president.json: 要特別注意,JSON 的內容要完全符合 JSON 格式規定,如果不符合,一般來說不會有錯誤訊息,只是程式就停止執行,不會有任何反應,debug 比較廢時。
[
    {
        "title":"Ma the bumbler",
        "sub-title":"A former heart-throb loses his shine",
        "date":"Nov 17th 2012 | TAIPEI | From the print edition",
        "content":"WHEN he was first elected in 2008, Taiwan’s president, Ma Ying-jeou, offered Taiwanese high hopes that the island’s economy would open a new chapter. He promised ground-breaking agreements with China to help end Taiwan’s growing economic marginalisation. At the time, Mr Ma’s image was of a clean technocrat able to rise above the cronyism and infighting of his party, the Kuomintang (KMT). He was a welcome contrast to his fiery and pro-independence predecessor, Chen Shui-bian, now in jail for corruption.<br/>Five years on, and despite being handily re-elected ten months ago, much has changed. In particular, popular satisfaction with Mr Ma has plummeted, to a record low of 13%, according to the TVBS Poll Centre. The country appears to agree on one thing: Mr Ma is an ineffectual bumbler."
    },
    {
        "title":"A Tsai is just a Tsai",
        "sub-title":"The election of an independence-leaning president would put Taiwan back in the international spotlight",
        "date":"Jan 9th 2016 | TAIPEI | From the print edition",
        "content":"UNDETERRED by the rain, the crowd leaps to its feet shouting “We’re going to win” in Taiwanese as their presidential candidate, Tsai Ing-wen, begins her stump speech. Some rattle piggy banks to show that their party, the Democratic Progressive Party (DPP), relies on, and serves, the little guy—as opposed to the ruling Kuomintang (KMT), backed by businesses and fat cats and one of the world’s richest political institutions. Taiwan’s voters go to the polls on January 16th in what is likely to prove a momentous election both for the domestic politics on the island and for its relations with the Communist government in China that claims sovereignty over it. Eight years of uneasy truce across the Taiwan Strait are coming to an end."
    }
]
現在進入主題,看一下程式怎麼寫 … 只有一個網頁,如下:
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<script type="text/javascript" src="<%=request.getContextPath()%>/js/jquery-1.12.3.min.js"></script>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>AJAX</title>

<style type="text/css">
    .button {
        background-color: #7CA05F;
        border: none;
        color: white;
        padding: 15px 32px;
        text-align: center;
        text-decoration: none;
        display: inline-block;
        font-size: 16px;
        margin: 4px 2px;
        cursor: pointer;
    }
</style>
    
<script type="text/javascript">
$(function() {
    $('#html-button .button').bind('click', (function() {
        $("#article").load('../html/bumblerMa.html');
    }));

    $('#json-button .button').bind('click', (function() {
        $.getJSON('../json/president.json', function(data) {
            $('#article').empty();
            $.each(data, function(entryIdx, entry) {
                var html = '';
                html += '<H1>' + entry['title'] + '</H1>';
                html += '<H3>' + entry['sub-title'] + '</H3>';
                html += '<DIV>' + entry['date'] + '</DIV>';
                html += '<br/>' + entry['content'] + '</br>';
                $('#article').append(html);
            }); 
        });
    }));
});
</script>

</head>
<body>

<div id="article"></div>
<div id="html-button">
    <input type="button" class="button" value="html"/>
</div>

<div id="json-button">
    <input type="button" class="button" value="json"/>
</div>


</body>
</html>
  • 綠色部份: 引入 jQuery 函式庫。
  • 藍色部份: 這是要顯示資料的地方,一開始沒有任何內容!
  • 黃色部份: 這表示要找到一個在 id="html-button" 的 tag 下,任何一個含有 class="button" 的 tag,及一個在 id="json-button" 的 tag 下,任何一個含有 class="button" 的 tag。
  • 紅色部份: 在網頁載入時,為這兩個按鍵 bind click 事件,這樣當這兩個按鍵被 click 時,就會執行 bind 時所指定的 function。
  • 紫色部份: 使用 load 將 載入的內容顯示在 tag 上,這就可以了解,為什麼這個 bumblerMa.html 不是完整的 html 檔了。
  • 橘色部份: 使用 getJSON 載入 json 檔,載入的資料會放在 data 那個變數裡,再透過 $.each 將 JSON 的內容讀出來,$.each 一次取出一個元素,以 president.json 的內容來說,共有兩個元素,每個元素有 title、sub-title、date、content 四項資料。
上面非同步抓取 json 資料的程式也可以改用如下的方法:
$('#json-button2 .button').bind('click', (function() {
    $.ajax({
        type: 'get',
        url: '../json/president.json',
        dataType: 'json',
        success: function(data, result) {
         $.each(data, function(entryIdx, entry) {
                $('#article').empty();
                var html = '';
                html += '<H1>' + entry['title'] + '</H1>';
                html += '<H3>' + entry['sub-title'] + '</H3>';
                html += '<DIV>' + entry['date'] + '</DIV>';
                html += '<br/>' + entry['content'] + '</br>';
                $('#article').append(html);
           }); 
        }
    });
}));

沒有留言:

張貼留言