LoginSignup
0
3

More than 5 years have passed since last update.

[HTML5]カスタムデータ属性の使い方(Ajax連携)

Last updated at Posted at 2017-05-02

"data-" で始まるカスタムデータ属性。存在は知っていても具体的に何に使うの?ということで、
例えば、外部API等からAjaxで取ってきた値と組み合わせて使えます。

表示対象のデータを表示する

HTMLファイル
<input type="hidden" name="item_id" value="1" data-description="あああ" class="hidden_item" /> 
<input type="hidden" name="item_id" value="2" data-description="いいい" class="hidden_item" /> 

<div id="description" />
getShowItemId(API)が返す値
{
  "_comment": "表示対象のIDです",
  "item_id": "2"
}
JSファイル
$(function(){
  // hiddenに隠しておいた値を取る
  var items = [];
  $.each($('.hidden_item'), function() {
    var itemId = $(this).val();
    items[itemId] = $(this).data("description");
  });

  $.ajax({
    url: 'https://' + window.location.hostname + '/getShowItemId',
    dataType: 'json',
    cache: false,
    timeout: 5000,
    success: function(response) {
      var description = items[response.item_id];
      $('#description').append(description);
    },
    error: function() {
      console.log('通信エラー');
    },
  });
});

ブラウザにはいいいが表示される。

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