Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationEventAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
3
Help us understand the problem. What are the problem?

More than 5 years have passed since last update.

@TTT00x

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

仕様

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();
});
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
3
Help us understand the problem. What are the problem?