LoginSignup
2
3

More than 5 years have passed since last update.

ajaxで取得したjsonをlodash製テンプレートに突っ込む

Last updated at Posted at 2016-02-16

仕様

jsonの情報をテンプレートに突っ込んで、回数分DOMを生成したい。

HTML

データ属性を付けた<div>内にloading.gifを入れておく。
入れとかなくても問題は無い。でもクルクルしてた方が格好いいと思う。

htnl
<div data-target-list="list">
    <img src="img/loading.gif">
</div>

JSON

JSON
[
  {
    "title": "kuma",
    "url": "http://kuma.com",
    "img": "kuma.png",
  },
  {
    "title": "tama",
    "url": "http://tama.com",
    "img": "tama.png",
  },
  {
    "title": "kiso",
    "url": "http://kiso.com",
    "img": "kiso.png",
  },
]

JS

  1. ajaxでjsonを取得。
  2. ajaxはdeferredオブジェクトを持っているので、宣言なしで.doneできる。
  3. lodashの_.templateでテンプレートを変数に格納。
  4. loading.gifを隠す。
  5. forで回して、テンプレートにjsonの情報を突っ込みつつ、DOM描画。

という流れ。

javascript
var list = function(){
    var $target = $('[data-target-list]');
    $.ajax({
        type: 'get',
        url: 'data/list.json',
        dataType: 'json'
    })
    .done(function(data){
        var temp = _.template(
            '<div class="primaryBox">' +
                '<a href="<%= url %>">' +
                    '<%= title %>' +
                '</a>' +
                '<img src="<%= img %>">' +
            '</div>'
        );
        $('.loading').css('display','none');
        for (var i=0; i < data.length; i++){
            $target.append(temp(data[i]));
        }
    });
};
$(function(){
    list();
});
2
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
3