12
11

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

jQueryでJsonデータをファイルから読み込み画面表示する

Last updated at Posted at 2016-08-08

Webページを一部自動更新にする」という記事を書いたので、
今度はその応用としてJsonデータを定期的に読み込んでそれを画面表示するコードを実装する。

Jsonデータ

読み込むためのjsonファイルを作成する。

[
    {
        "name": "Tanaka",
        "age": 69
    },
    {
        "name": "Yoshida",
        "age": 24
    }
]

定期的に読み込む

前回までのおさらいを含めてざっと作成。
とりあえず問題ないかな?

<html>
  <head>
    <title>test</title>
    <script type="text/javascript" src="js/jquery-3.1.0.min.js"></script>
    <script type="text/javascript" src="js/jquery.periodicalupdater.js"></script>
    <script type="text/javascript">
      $(function(){
        var $label = [];
        $label.push($( "#Tanaka" ));
        $label.push($( "#Yoshida" ));

        $.PeriodicalUpdater('./data.json',{
          method: 'get',
          minTimeout: 1000,
          type: 'json',
          multiplier:1,
          maxCalls: 0
        },

        function(data){
          var len_data = data.length;

          for( var i = 0; i < len_data; i++ ){
            if( data[i].name == "Tanaka" ){
              $label[0].text( data[i].name + " : " + data[i].age );
            }else if( data[i].name == "Yoshida" ){
              $label[1].text( data[i].name + " : " + data[i].age );
            }
          }
        });
      });
    </script>
  </head>
  <body>
    <div id="Tanaka"></div>
    <div id="Yoshida"></div>
  </body>
</html>

改良計画

下記部分はまだ簡略化できるはず。
特に label への処理にほぼ変更はないため積極的に処理をまとめたい。

          for( var i = 0; i < len_data; i++ ){
            if( data[i].name == "Tanaka" ){
              $label[0].text( data[i].name + " : " + data[i].age );
            }else if( data[i].name == "Yoshida" ){
              $label[1].text( data[i].name + " : " + data[i].age );
            }
          }

ちょっと考え中。。

12
11
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
12
11

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?