7
7

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.

テーブルのカラムごとにAjaxで値を取得して反映する

Posted at

Ajaxで値を取ってテーブルに値をいれる自分の中でのテンプレ。

例えばこんなHTMLがあったとして

  <table>
    <tr>
      <td class="targetHogehoge">
        <div>Loading...</div>
        <input type="hidden" name="param1" value="p1" />
        <input type="hidden" name="param2" value="p2" />
        <input type="hidden" name="param3" value="p3" />
      </td>
    </tr>
    <tr>
      <td class="targetHogehoge">
        <div>Loading...</div>
        <input type="hidden" name="param1" value="pp1" />
        <input type="hidden" name="param2" value="pp2" />
        <input type="hidden" name="param3" value="pp3" />
      </td>
    </tr>
    <tr>
      <td class="targetHogehoge">
        <div>Loading...</div>
        <input type="hidden" name="param1" value="ppp1" />
        <input type="hidden" name="param2" value="ppp2" />
        <input type="hidden" name="param3" value="ppp3" />
      </td>
    </tr>
  </table>

Loading...にAjaxで取った値を表示されるようにするには。

スクリプト書くとこんな感じ

$(function($){
  getHogeHogeData();
});

function getHogeHogeData() {
  var targetColumn = $(".targetHogehoge:first");
  if (targetColumn.length == 0) {
    return;
  }
  var param1 = targetColumn.children("input[name='param1']").val();
  var param2 = targetColumn.children("input[name='param2']").val();
  var param3 = targetColumn.children("input[name='param3']").val();
  var hash = new Date().getTime();
  $.ajax({
      type : "get",
      url :  "hhh/ooo/ggg/eee",
      dataType : "html",
      data : {
        "parameter1" : param1,
        "parameter2" : param2,
        "parameter3" : param3,
        "hash" : hash
      },
      error : function(XMLHttpRequest, status) {
        targetColumn.children("div").html(status);
        targetColumn.removeClass("targetHogehoge");
        getHogeHogeData();
      },
      success : function(data) {
        targetColumn.children("div").html(data);
        targetColumn.removeClass("targetHogehoge");
        getHogeHogeData();
      }
  });
}

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?