概要
- 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);
});