[JavaScript] jQuery使Ajax通信JSON取得する方法

2 min read
hiroweb developer

概要

  • JSONを吐き出すAPIのデータを取得する。
  • ただし、jQueryは使用できないものとする。

想定

レガシーブラウザは念頭にない。(レガシー考慮するなら jQuery 使おう!)

jQueryを使用した場合

ちなみにjQueryを使用できるのであれば以下のようなコードで良い。
$.getJSON("http://localhost/api/hoge", data, function(json){
    console.log(json);
});

簡潔に記述することができる。

Vanillaで実装する

jQuery と仕様を合わせるつもりはないが、以下の様な実装で実現可能。
function getJSONData(url, callback) {
  var xhr = new XMLHttpRequest();

  xhr.onerror = function () {
    console.log('error');
  };

  xhr.onreadystatechange = function () {
    if (this.readyState === 4 && this.status === 200) {
      var response = this.response;
      if (typeof response === 'string') {
        response = JSON.parse(response);
      }

      callback(response, header);
    }
  };

  xhr.open('GET', url, true);
  xhr.responseType = 'json';
  xhr.send();
}

課題:

  • JSON.parseのラッパーを用意したほうが良いかも
  • ステータスコードを返そう

使い方

getJSONData("http://localhost/api/hoge", function(json) {
    console.log(json);
});

おまけ

こういうのもある。

jquery.ajax