Đáp án bài tập Javascript cơ bản Ajax – Thông tin Pokemon (Pokedex)

Giao diện trang chủ sẽ liệt kê các pokemon (pokemon.html)

thiết kế pokedex, pokemon

Khi vào chi tiết của 1 pokemon (poke.html) ta sẽ thấy mỗi pokemon sẽ nằm trong 1 hay nhiều loại (types), hay các hệ: lửa, nước, bay được, …
Giao diện hiển thị mỗi loại (type.html) sẽ liệt kê các Pokemon giống trang chủ

pokemon.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>Document</title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
    <script src="pokemon.js"> </script>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
</head>
<body>
        <div class="container">
          <div class="row">

          </div>
        </div>
</body>
</html>
$(document).ready(function() {
    showData("https://pokeapi.co/api/v2/pokemon/?limit=12");
});

function showData(data) {
    // $(".spinner-border").show();
    $.getJSON(data, function(pokemon) {
        let pika = "";
        // console.log(pokemon);
        pokemon.results.forEach(pikachu => {
            const { name, url } = pikachu;
            let id = url
                .replace("https://pokeapi.co/api/v2/pokemon/", "")
                .replace("/", "");
            console.log(id);

            // pika += `<div class="col-6 col-md-4 col-lg-3">
            // <div>
            //  <a href="poke.html?id=${id}">
            //     <img src="https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/${id}.png" alt="${name}">
            //  </a>
            // </div>
            // </div>`;
            pika += `
            <div class="card card col-6 col-md-4 col-lg-3">
            <a href="poke.html?id=${id}">
            <img class="card-img-top" src="https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/${id}.png" 
            alt="${name}" />
            </a>
            <div class="card-body">
            <div class="text-center">${id}</div>
            <div class="text-center">${name}</div>
                </div>
                </div>
            `;
        });
        $(".row").html(pika);
    }).done(function() {
        console.log("second success");
        $(".spinner-border").hide();
    });
}

poke.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">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
    <script src="poke.js"> </script>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
    <style> 
        body{
            padding: 50px;
        }
    </style>


</head>
</head>
<body>
        <header><a href="pokemon.html">Home</a></header>
        <div>
            <img src="" alt="">
            <h2 id="pokename"></h2>
        </div>
        <table class="table">
                <thead>
                  <tr>
                    <th scope="col">National №</th>
                    <th scope="col" id="no"></th>
                  </tr>
                </thead>
                <tbody>
                  <tr>
                    <th scope="row">Type</th>
                    <td id="type"></td>
                  </tr>
                  <tr>
                    <th scope="row">Weight</th>
                    <td id="weight"></td>
                  </tr>
                  <tr>
                    <th scope="row">Height</th>
                    <td id="height"></td>
                  </tr>
                  <tr>
                    <th scope="row">Abilities</th>
                    <td id="abl"></td>
                  </tr>
                </tbody>
              </table>
              <h2>Stats</h2>
              <table class="table">
                    <tbody>
                        <tr>
                            <th scope="row">HP</th>
                            <td id="hp"></td>
                        </tr>
                        <tr>
                            <th scope="row">Attack</th>
                            <td id="att"></td>
                        </tr>
                        <tr>
                            <th scope="row">Defense</th>
                            <td id="def"></td>
                        </tr>
                        <tr>
                            <th scope="row">Sp. Atk</th>
                            <td id="spAtk"></td>
                        </tr>
                        <tr>
                            <th scope="row">Sp. Def</th>
                            <td id="spDef"></td>
                        </tr>
                        
                        <tr>
                            <th scope="row">Speed</th>
                            <td id="speed"></td>
                        </tr>
                        <tr>
                          <th scope="row">Total</th>
                          <td id="total"></td>
                        </tr>
                        
                    </tbody>
                </table>

                
                
</body>

</html>
var params = new URLSearchParams(window.location.search);
$(document).ready(function() {
    $.getJSON(
        `https://pokeapi.co/api/v2/pokemon/${params.get("id")}/`,
        function(data) {
            let poki = "";
            const {
                name,
                abilities,
                types,
                stats,
                height,
                weight,
                id,
                moves
            } = data;
            // console.log(types);
            $("#no").html(id.toString().padStart(3, "0"));
            let type = "";
            types.forEach(item => {
                // console.log(item.type.name);
                let classType = getClass(item.type.name);
                console.log(classType);
                type += `<a href="type.html?type=${
                    item.type.name
                }"class="${classType}" >${item.type.name}</a>`;
            });
            let total = 0;
            stats.forEach(item => {
                total += item.base_stat;
            });

            console.log(moves);

            let ablString = "";
            abilities.forEach(item => {
                // console.log(item.abilities.name);
                if (item.is_hidden) {
                    ablString += `<div>${
                        item.ability.name
                    } (hidden ability)</div>`;
                } else {
                    ablString += `<div>${item.ability.name}</div>`;
                }
            });
            $("#speed").html(stats[0].base_stat);
            $("#spDef").html(stats[1].base_stat);
            $("#spAtk").html(stats[2].base_stat);
            $("#def").html(stats[3].base_stat);
            $("#att").html(stats[4].base_stat);
            $("#hp").html(stats[5].base_stat);
            $("#total").html(total);
            $("#abl").html(ablString);
            $("#type").html(type);
            $("img").attr(
                "src",
                `https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/${id}.png`
            );
            $("#pokename").text(name);
            $("body").append(poki);
            $("#weight").html(weight);
            $("#height").html(height);
            console.log(data);
        }
    );
});

function getClass(type) {
    if (type == "grass") {
        return "btn btn-success";
    }
    if (type == "fire") {
        return "btn btn-danger";
    }
    if (type == "flying") {
        return "btn btn-info";
    }
    return "btn btn-light";
}

type.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>Document</title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
    <script src="type.js"> </script>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
</head>
<body>
    <header><a href="pokemon.html">Home</a></header>
        <div class="container">
          <div class="row">
          </div>
        </div>
</body>
</html>
var params = new URLSearchParams(window.location.search);
$(document).ready(function() {
    showData(`https://pokeapi.co/api/v2/type/${params.get("type")}/`);
});

function showData(url) {
    // $(".spinner-border").show();
    $.getJSON(url, function(data) {
        let pika = "";
        data.pokemon.forEach(item => {
            const { name, url } = item.pokemon;
            let id = url
                .replace("https://pokeapi.co/api/v2/pokemon/", "")
                .replace("/", "");
            console.log(id);
            pika += `
            <div class="card card col-6 col-md-4 col-lg-3">
            <a href="poke.html?id=${id}">
            <img class="card-img-top" src="https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/${id}.png" 
            alt="${name}" />
            </a>
            <div class="card-body">
            <div class="text-center">${id}</div>
            <div class="text-center">${name}</div>
                </div>
                </div>
            `;
        });
        $(".row").html(pika);
    }).done(function() {
        console.log("second success");
        $(".spinner-border").hide();
    });
}