LoginSignup
0

More than 3 years have passed since last update.

posted at

updated at

AJAXでGitHubのAPIからユーザー情報を取得

概要

ボタンを押すとAPIを通じて、GitHubのユーザーが一覧表示されます。

環境

MacOS Mojave
xamppをインストール&起動している前提で記述します。

ディレクトリ構成

htdocs
├── ajax.html

HTMLの雛形

下記ファイルをhtdocsへ配置します。

ajax.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Ajax - External API</title>
</head>
<body>
    <!-- buttonタグの設置 -->
    <button id="button">GitHubのユーザー読み込み</button>
    <br><br>
    <h1>GitHub Users</h1>
    <div id="users"></div>
</body>
</html>

APIの取得

認証等が特に必要ない下記URLから取得します。
https://api.github.com/users

Ajaxの記述

URLからAPIを取得する

ajax.html
<body>
    <button id="button">GitHubのユーザー読み込み</button>
    <br><br>
    <h1>GitHub Users</h1>
    <div id="users"></div>

    <script>
        // Ajax処理記述
        document.getElementById('button').addEventListener('click', loadUsers);

        // APIを読み込む
        function loadUsers(){
            var xhr = new XMLHttpRequest();
            xhr.open('GET', 'https://api.github.com/users', true);

            xhr.onload = function(){
                if(this.status == 200){
                    // JSONを変数に格納できる形に変更する
                    var users = JSON.parse(this.responseText);
                }
            }

            xhr.send();
        }
    </script>

取得した情報をHTMLに表示させる

ajax.html
    <script>
        // Ajax処理記述
        document.getElementById('button').addEventListener('click', loadUsers);

        // APIを読み込む
        function loadUsers(){
            var xhr = new XMLHttpRequest();
            xhr.open('GET', 'https://api.github.com/users', true);

            xhr.onload = function(){
                if(this.status == 200){
                    // JSONを変数に格納できる形に変更する
                    var users = JSON.parse(this.responseText);

                    // for文でuser情報を一つずつ抜き出す
                    var output = '';
                    for(var i in users){
                        output +=
                        '<div class="user">' +
                        '<img src="'+users[i].avatar_url+'" width="70" height="70">' +
                        '<ul>' +
                        '<li>ID: '+users[i].id+'</li>' +
                        '<li>ID: '+users[i].login+'</li>' +
                        '</ul>' +
                        '</div>';
                    }
                    // HTMLに抜き出した情報を表示させる
                    document.getElementById('users').innerHTML = output;
                }
            }

            xhr.send();
        }
    </script>

この状態で、localhost/ajax.htmlにアクセス→ボタンを押すと、ユーザ一覧が表示されます。

見た目を良くする

見た目が寂しいので、cssを記述します。

ajax.html
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Ajax - External API</title>
    <!-- cssの記述 -->
    <style>
        .user{
            display: flex;
            background: #f4f4f4;
            padding: 10px;
            margin-bottom: 10px;
        }

        .user ul{
            list-style: none;
        }
    </style>

完成

最終的なコードは下記のとおり

ajax.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Ajax - External API</title>
    <!-- cssの記述 -->
    <style>
        .user{
            display: flex;
            background: #f4f4f4;
            padding: 10px;
            margin-bottom: 10px;
        }

        .user ul{
            list-style: none;
        }
    </style>
</head>
<body>
    <button id="button">GitHubのユーザー読み込み</button>
    <br><br>
    <h1>GitHub Users</h1>
    <div id="users"></div>

    <script>
        // Ajax処理記述
        document.getElementById('button').addEventListener('click', loadUsers);

        // APIを読み込む
        function loadUsers(){
            var xhr = new XMLHttpRequest();
            xhr.open('GET', 'https://api.github.com/users', true);

            xhr.onload = function(){
                if(this.status == 200){
                    // JSONを変数に格納できる形に変更する
                    var users = JSON.parse(this.responseText);

                    // for文でuser情報を一つずつ抜き出す
                    var output = '';
                    for(var i in users){
                        output +=
                        '<div class="user">' +
                        '<img src="'+users[i].avatar_url+'" width="70" height="70">' +
                        '<ul>' +
                        '<li>ID: '+users[i].id+'</li>' +
                        '<li>ID: '+users[i].login+'</li>' +
                        '</ul>' +
                        '</div>';
                    }
                    // HTMLに抜き出した情報を表示させる
                    document.getElementById('users').innerHTML = output;
                }
            }

            xhr.send();
        }
    </script>
</body>
</html>

参照元

AJAX Crash Course (Vanilla JavaScript)

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
What you can do with signing up
0