javascript axiosを使ってjsonデータを取得する
- 2020.10.15
- javascript
- javascript

javascriptで、axiosを使用して、jsonデータを取得するサンプルコードを記述してます。自分はaxiosを使用するのが、jsonデータとのやり取りは一番楽かと思います。
環境
- OS windows10 pro 64bit
- Apache 2.4.43
- ブラウザ chrome 84.0.4147.105
axios使い方
axiosは、以下を読み込むだけで使用可能です。
1 |
<script src="https://unpkg.com/axios/dist/axios.min.js"></script> |
利用方法も簡単で、以下のコードだけでjsonが取得できます。
1 2 3 4 |
axios.get('https://jsonplaceholder.typicode.com/todos/') .then(res => console.log(res.data)) .catch(err => console.error(err)) .finally(res => console.log('finally')) |
実行結果

サンプルコード
以下は、
「実行」ボタンをクリックすると、JSONデータを取得してparseし、フロントに表示する
サンプルコードとなります。
※cssには「bootstrap5」を使用してます。「bootstrap5」は、IEのサポートを終了してます。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 |
<!DOCTYPE html> <html lang="ja"> <head> <meta charset="utf-8"> <title>mebeeサンプル</title> <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700|Material+Icons"> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/css/bootstrap.min.css"> <script src="https://unpkg.com/axios/dist/axios.min.js"></script> </head> <style> .main { margin: 0 auto; margin-top: 200px; display: flex; flex-direction: column; align-items: center; font-size: 30px; } </style> <script> function hoge() { jsonGet(); } async function jsonGet() { try { const res = await axios.get('https://jsonplaceholder.typicode.com/todos/'); // jsonを文字列化してparse const items = JSON.parse(JSON.stringify(res.data)); // 表示用 disp(items,"txt"); } catch (err) { console.error(err); } } //フロントに表示する関数 function disp(arr, id) { let text = []; // for ofを使用 for (let item of arr) { text.push('<li class="list-group-item">' + JSON.stringify(item) + '</li>'); } //innerHTMLを使用して表示 document.getElementById(id).innerHTML = text.join(''); } window.onload = () => { // クリックイベントを登録 btn.onclick = () => { hoge(); }; // document.getElementById('btn');を省略 } </script> <body> <div class="main container"> <h2><span class="badge bg-primary">表示</span></h2> <ul id="txt" class="list-group list-group-flush"></ul> <div class="row"> <button id="btn" type="button" class="btn btn-warning"> 実行 </button> </div> </div> </body> </html> |
jsonが表示されていることが確認できます。

-
前の記事
C# textboxの値を全選択する 2020.10.15
-
次の記事
Rails アクションから別テンプレートを表示させる 2020.10.15
コメントを書く