如何解除PokéAPI默认限制?无法获取ID>20的宝可梦数据
问题解决:PokéAPI查询编号大于20的宝可梦无数据
问题原因
核心问题是基础请求URL错误。PokéAPI的默认宝可梦列表接口(https://pokeapi.co/api/v2/pokemon)不带参数时仅返回前20条数据,如果你把用户输入的编号直接拼在这个列表URL后面,会生成无效请求地址,自然无法获取20号以后的宝可梦数据。
解决方案
1. 修正基础请求URL
将nationalDex变量改为单只宝可梦的查询接口,这个接口支持直接拼接任意编号或名称:
const nationalDex = 'https://pokeapi.co/api/v2/pokemon/';
2. 优化后的完整代码
// 假设$input、$pokemon、$moveSet是已定义的jQuery元素 const nationalDex = 'https://pokeapi.co/api/v2/pokemon/'; function getNationalDex(event) { event.preventDefault(); const userInput = $input.val().trim(); // 去除输入首尾空格 if (!userInput) return; $input.val(''); $moveSet.empty(); // 清空之前的招式列表,避免内容叠加 $.ajax(nationalDex + userInput) .then((data) => { console.log(data); $pokemon.text(data.name); // 遍历渲染招式列表 for (const move of data.moves) { $("<p>", { class: "moves", // 不要用重复id,class即可满足样式需求 }) .text(move.move.name) .appendTo($moveSet); }; // 补充类型显示逻辑(示例:显示第一个类型) if (data.types.length > 0) { // 若有$type元素,可取消注释使用 // $type.text(data.types[0].type.name); } }) .catch(function (error) { console.error('请求失败:', error); // 用error级别日志更醒目 }); }
关键优化点说明
- URL修正:改用单只宝可梦详情接口,彻底解除编号限制;
- 输入处理:添加
trim()过滤无效空格输入; - DOM清理:每次请求前清空招式容器,避免新旧内容叠加;
- ID规范:移除重复的
id="move"(页面内id必须唯一,class足够实现样式控制); - 错误提示:改用
console.error更直观展示问题; - 类型数据:补全了类型字段的正确取值方式(
data.types[0].type.name)。
内容的提问来源于stack exchange,提问作者Claude Allen
相关产品推荐
相关产品推荐

