概要
- JSONを吐き出すAPIのデータを取得する。
- ただし、jQueryは使用できないものとする。
想定
レガシーブラウザは念頭にない。(レガシー考慮するなら jQuery 使おう!)jQueryを使用した場合
ちなみにjQueryを使用できるのであれば以下のようなコードで良い。$.getJSON("http://localhost/api/hoge", data, function(json){
    console.log(json);
});簡潔に記述することができる。
$.getJSON("http://localhost/api/hoge", data, function(json){
    console.log(json);
});簡潔に記述することができる。
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();
}
課題:
getJSONData("http://localhost/api/hoge", function(json) {
    console.log(json);
});