トップページ >  Ajax >  1分おきに画像を置き換えるには
初版2010/05/07: 最終更新日2010/05/07
1分おきに画像を置き換えるには
目次
1分おきに画像を置き換えるには
1分おきに画像を置き換えるサンプル
1分おきに画像を置き換えるには
1分おきに画像を置き換えるには、PeriodicalUpdaterを使用する事で実現できます。
今回は、サーバ上のデータベースで管理している画像情報を取得してクライアントの画像を変更しようと思います。 画像情報を取得する際に、jsonを用いたデータ連携をします。
1分おきに画像を置き換えるサンプル
  var myajax;

  function execute()
  {
    // パラメータ(表示時間)生成
    now = new Date();
    hh  = now.getHours().toString();
    if (hh.length == 1)
    {
      hh = '0' + hh;
    }
    mm  = now.getMinutes().toString();
    if (mm.length == 1)
    {
      mm = '0' + mm;
    }
    tm  = hh + mm;

    // 取得処理実行
    myajax = new Ajax.PeriodicalUpdater(
      "container",
      "http://localhost/test.php",
      {
        method     : "get",
        parameters : "tm=" + tm,
        frequency  : 60,
        onSuccess  : function(request)
        {
          // 読込み成功時の処理
          response = eval('(' + request.responseText + ')');
          //
          $('name').innerHTML     = response.Name;
          $('recipe').innerHTML   = response.Recipe;
          if (response.Time != '-')
          {
            tm  = response.Time;
            hh  = response.Time.substring(0, 2);
            //
            str = '<img src=';
            str = str.concat("http://localhost/images/" + tm);
            str = str.concat('.jpg />');
            //
            $('center').innerHTML   = str;
          }

          // パラメータ(表示時間)生成
          now = new Date();
          hh  = now.getHours().toString();
          if (hh.length == 1)
          {
            hh = '0' + hh;
          }
          mm  = now.getMinutes().toString();
          if (mm.length == 1)
          {
            mm = '0' + mm;
          }
          tm  = hh + mm;

          par = myajax.options.parameters;
          var hash   = $H(par).toQueryString().parseQuery();
          hash["tm"] = hh + mm;
          hash["id"] = Math.random();
          myajax.options.parameters = $H(hash);
        },
        onComplete : function(request)
        {
          // 読込み完了時の処理
          alert('読込みが完了しました。');
        },
        onFailure  : function(request)
        {
          // 読込み失敗時の処理
          alert('読込みに失敗しました。');
        },
        onException: function (request)
        {
          // 読込みエラーの処理
          alert('読込み中にエラーが発生しました。');
        }
      }
    );
  }