axiosを使ってjsonファイルを取得する

PromiseベースのHTTPクライアントのaxiosを使って、jsonファイルの取得を試してみます。

使い方

まずはaxiosのインストールですが、npmやbowerなどいくつか方法が用意されています。
今回はCDNを使ってみます。

<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>

取得するjsonは以下のデータを使用します。

sample.json

{
	"vtuber": [
		{ "name": "Lize Helesta" },
		{ "name": "Ange Katrina" },
		{ "name": "Toko Inui" }
	]
}

実際にjsonを取得してみます。
取得は axios.get(‘取得するURL’) の形で指定します。

axios.get('./sample.json')
	.then(function (response) {
		// 取得成功時
		console.log('取得成功', response);
		var data = response.data.vtuber;

		// ページにjsonの情報を追加
		var fragment = document.createDocumentFragment();
		for (var i = 0; i < data.length; i++) {
			var item = document.createElement('div');
			item.textContent = data[i]['name'];
			fragment.appendChild(item);
		}
		document.body.appendChild(fragment);
	})
	.catch(function (error) {
		// 取得失敗時
		console.log('取得失敗', error);
	})
	.then(function () {
		// 取得成功・失敗の処理後に共通で実行
	});

これで問題ないかと思ったのですが、IE11だと「’Promise’ は定義されていません。」のようなエラーとなっていました。
axiosでjsonを取得するデモページ

IE11でPromiseが使えないことが原因なので、polyfillを読み込むようにするといいようです。

<script src="https://www.promisejs.org/polyfills/promise-7.0.4.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>

これでIE11でもjsonファイルの取得ができました。
axiosでjsonを取得するデモページ2

参考サイト

このエントリーをはてなブックマークに追加

関連記事

コメントを残す

メールアドレスが公開されることはありません。
* が付いている欄は必須項目です

CAPTCHA


コメントが承認されるまで時間がかかります。

2024年4月
 123456
78910111213
14151617181920
21222324252627
282930