新手求教:如何在HTML中调用REST API实现宝可梦API搜索页面
Pokémon Search API Implementation for Beginners
Hey there! I totally get it—diving into APIs can feel confusing at first, especially when tutorials are overly technical. Let's get your simple Pokémon search page up and running with straightforward JavaScript, no fancy frameworks needed.
First, let's tweak your initial HTML to work with plain JS (I removed the v-html since it's a Vue-specific feature, which you didn't mention using):
<!DOCTYPE html> <html> <body> <h1>Pokémon Search API</h1> <input id="pokeName" type="text" placeholder="Enter Pokémon name" style="width:20%"/> <button onclick="searchPokemon()">Find Pokémon By Name</button> <h3>Results</h3> <div id="pokeResults"></div> <script> // Our core search function function searchPokemon() { // Grab input value and normalize to lowercase (PokéAPI expects lowercase names) const pokemonName = document.getElementById('pokeName').value.toLowerCase(); const resultsDiv = document.getElementById('pokeResults'); // Clear previous results so we start fresh resultsDiv.innerHTML = ''; // Guard against empty input if (!pokemonName) { resultsDiv.innerHTML = '<p>Please enter a Pokémon name first!</p>'; return; } // Fetch data from PokéAPI fetch(`https://pokeapi.co/api/v2/pokemon/${pokemonName}`) .then(response => { // Handle case where Pokémon isn't found (404 error) if (!response.ok) { throw new Error('Whoops! That Pokémon doesn\'t exist.'); } return response.json(); }) .then(data => { // Build HTML to display key Pokémon details const resultContent = ` <h4>${data.name.charAt(0).toUpperCase() + data.name.slice(1)}</h4> <img src="${data.sprites.front_default}" alt="${data.name} sprite" style="width:150px"/> <p>ID: ${data.id}</p> <p>Height: ${data.height / 10} m</p> <p>Weight: ${data.weight / 10} kg</p> <h5>Types:</h5> <ul> ${data.types.map(type => `<li>${type.type.name.charAt(0).toUpperCase() + type.type.name.slice(1)}</li>`).join('')} </ul> `; // Insert content into the results div resultsDiv.innerHTML = resultContent; }) .catch(error => { // Show user-friendly error message resultsDiv.innerHTML = `<p>${error.message}</p>`; }); } </script> </body> </html>
Let's break down what this does:
- Input Handling: We convert the input to lowercase because the PokéAPI requires all-lowercase names for its endpoints—this ensures it works even if the user types "Pikachu" or "PIKACHU".
- Fetch Request: We use the browser's built-in
fetch()function to call the PokéAPI endpoint for the specified Pokémon. - Response & Error Handling:
- If the API returns an error (like a 404 when the Pokémon doesn't exist), we catch it and show a simple message.
- If the request succeeds, we parse the JSON data and build HTML to display useful details: the Pokémon's name (capitalized), sprite image, ID, height/weight (converted to meters/kilograms), and types.
- Clean UI: We clear previous results each time the button is clicked so the page doesn't get cluttered with old searches.
Quick Extra Tips:
- You can explore the full API response (by logging
datato the console withconsole.log(data)) to add more details, like abilities or base stats. - The sprite image uses
front_default, but the API has other sprite options (like shiny versions) if you want to expand later.
内容的提问来源于stack exchange,提问作者Bunny




