dayjournal memo

Total 975 articles!!

Riot.js #006 – 外部JSON読み込み

Yasunori Kirimoto's avatar

riot-js_001_01


今回は、Riot.jsで外部JSONを読み込む方法を紹介します。


外部JSONを読み込むには下記のように記述します。


index.html


<!DOCTYPE html>
<html lang="ja">
    <head>

        <meta charset="UTF-8">
        <title>Riot.js sample</title>

        <script src="./library/jquery-2.1.4/jquery-2.1.4.min.js"></script>

        <script src="./library/riot/riot+compiler.js"></script>

        <script src="./tag/sample.tag" type="riot/tag"></script>

    </head>
    <body>

        <sample></sample>
        <sample2></sample2>

        <script>riot.mount('*');</script>

    </body> 
</html>

sample.tag


<sample>

    <p each={list}>{name} {age}</p>

    <style scoped>

        p {
            color: #00AA00;
        }

    </style>

    <script>

        fetch('./json/sample.json')
            .then( function(data) {
                return data.json();
            })
            .then( function(json) {
                this.list = json;
                this.update();
            }.bind(this));

    </script>

</sample>

<sample2>

    <h2 each={list}>{no} {value}</h2>

    <style scoped>

        h2 {
            color: #0D47A1;
        }

    </style>

    <script>

        $.getJSON("./json/sample2.json", function(json){
            this.list = json;
            this.update();
        }.bind(this));

    </script>

</sample2>

sample.json


[
    {
        "name": "山田",
        "age": "20"
    },
    {
        "name": "佐藤",
        "age": "30"
    },
    {
        "name": "近藤",
        "age": "25"
    }
]

sample2.json


[
    {
        "no": "1",
        "value": "aaa"
    },
    {
        "no": "2",
        "value": "bbb"
    },
    {
        "no": "3",
        "value": "ccc"
    }
]

index.htmlを実行すると下記のようにブラウザで表示されます。

riot-js_006_01


Fetch APIでJSON読み込みpタグで表示:


    <p each={list}>{name} {age}</p>

    <script>

        fetch('./json/sample.json')
            .then( function(data) {
                return data.json();
            })
            .then( function(json) {
                this.list = json;
                this.update();
            }.bind(this));

    </script>

jQueryでJSON読み込みh2タグで表示:


    <h2 each={list}>{no} {value}</h2>

    <script>

        $.getJSON("./json/sample2.json", function(json){
            this.list = json;
            this.update();
        }.bind(this));

    </script>

外部JSONを読み込む場合は、Fetch APIやXMLHttpRequestを利用可能です。外部ライブラリとも競合が少ないのでjQueryでJSON読み込みも可能です。



book

Q&A