/get のデータを段階的に表示する

この教材では、同じ /get API を使って、次の 4 段階で表示方法を学びます。
すべて「コードを写して、自分の HTML で動かす」ことを前提にしています。

  1. JSONだけを表示する
  2. JSONを1行の文字列として表示する
  3. 1件ずつ改行して表示する
  4. 表(table)で表示して完成形にする

① JSONだけを表示する

まずは、サーバーから返ってきた JSON を「そのまま」表示します。


<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<title>① JSONだけを表示する</title>
</head>
<body>

<h1>① JSONだけを表示する</h1>

<pre id="output">ここに結果が表示されます</pre>

<script>
// ① JSONだけを表示する
const server = "https://ome.funnygeekjp.com/api3004";

async function step1() {
    const url = server + "/get";
    const response = await fetch(url);
    const text = await response.text();  // JSONをパースしない
    document.getElementById("output").textContent = text;
}

step1(); // ページを開いたら実行
</script>

</body>
</html>

② JSONを1行の文字列として表示する

次に、JSONをパースしてから JSON.stringify() で 1 行の文字列にします。


// ② JSONを1行の文字列として表示する
async function step1() {
    const url = server + "/get";
    const response = await fetch(url);
    const jsonObj = await response.json();

    const oneLine = JSON.stringify(jsonObj);  // 1行のJSON文字列
    document.getElementById("output").textContent = oneLine;
}

③ 1件ずつ改行して表示する

配列の中身をループで取り出し、改行を使って読みやすくします。


// ③ 1件ずつ改行して表示する
async function step1() {
    const url = server + "/get";
    const response = await fetch(url);
    const jsonObj = await response.json();

    let text = "";
    jsonObj.forEach(item => {
        const date = item.created_at.substring(0, 10);  // 日付だけ
        text += `ID: ${item.id}\n`;
        text += `Title: ${item.title}\n`;
        text += `Memo: ${item.memo}\n`;
        text += `Created: ${date}\n`;
        text += `------------------------------\n`;
    });

    document.getElementById("output").textContent = text;
}

④ 表(table)で表示して完成形にする

最後に、HTML の <table> を使って一覧表にします。


// ④ 表(table)で表示して完成形にする
async function step1() {
    const url = server + "/get";
    const response = await fetch(url);
    const jsonObj = await response.json();

    let html = "<table border='1' cellpadding='5'>";
    html += "<tr><th>ID</th><th>Flag</th><th>Title</th><th>Memo</th><th>Created</th></tr>";

    jsonObj.forEach(item => {
        const date = item.created_at.substring(0, 10);
        html += `
            <tr>
                <td>${item.id}</td>
                <td>${item.flag}</td>
                <td>${item.title}</td>
                <td>${item.memo}</td>
                <td>${date}</td>
            </tr>
        `;
    });

    html += "</table>";

    document.getElementById("output").innerHTML = html;
}