Help us understand the problem. What is going on with this article?

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

More than 3 years have passed since last update.

仕様

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();
});
TTT00x
エンジニア見習い
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
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  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
ユーザーは見つかりませんでした