You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

原生JavaScript调用Pixabay API时无法获取图片ID值的问题

解决Pixabay API图片详情页动态生成问题

你当前的代码已经在列表页正确获取了图片ID(let imgId = item.id),并通过跳转链接传递了ID参数,问题出在详情页(photos.html)未提取URL中的ID参数,无法获取对应图片的详情数据。以下是完整的解决方案:

1. 列表页跳转链接优化(可选)

你当前的跳转链接是photos.html?id=${imgId},如果想要实现类似photos.html/id/图片名称的友好URL格式,静态页面可采用哈希路由(无需服务器配置),修改列表页的a标签代码:

editorChoice.innerHTML += `
<div class="col-lg-4 card">
  <img id="${imgId}" src="${imgPreview}" class="img-responsive center-block" alt="${imgTag}"/>
  <!-- 用哈希路由实现友好URL,编码图片名称避免特殊字符 -->
  <a href="photos.html#/${imgId}/${encodeURIComponent(imgTag.split(',')[0].trim())}">
    <p class="text-center">${imgTag}</p>
  </a>
</div>`;

2. 详情页(photos.html)添加数据获取与渲染代码

在photos.html的</body>标签前添加以下JavaScript代码,用于提取ID、调用API并渲染详情:

async function renderImageDetails() {
  // 提取URL中的ID参数(兼容两种URL格式)
  let imgId;
  // 处理哈希路由格式(photos.html#/123/风景)
  if (window.location.hash) {
    const hashParts = window.location.hash.slice(2).split('/');
    imgId = hashParts[0];
  } else {
    // 处理原始查询参数格式(photos.html?id=123)
    const urlParams = new URLSearchParams(window.location.search);
    imgId = urlParams.get('id');
  }

  if (!imgId) {
    document.getElementById('imageDetails').innerHTML = '<p>未找到有效图片ID</p>';
    return;
  }

  // 调用Pixabay API获取单张图片详情
  const apiKey = '12345'; // 替换为你的真实API Key
  try {
    const response = await fetch(`https://pixabay.com/api/?key=${apiKey}&id=${imgId}`);
    const data = await response.json();

    if (data.hits.length === 0) {
      document.getElementById('imageDetails').innerHTML = '<p>未找到对应图片</p>';
      return;
    }

    const image = data.hits[0];
    // 渲染详情内容
    const detailsHtml = `
      <div class="card mb-3">
        <img src="${image.largeImageURL}" class="card-img-top" alt="${image.tags}">
        <div class="card-body">
          <h5 class="card-title">${image.tags}</h5>
          <div class="row text-muted small">
            <div class="col">浏览量: ${image.views.toLocaleString()}</div>
            <div class="col">下载量: ${image.downloads.toLocaleString()}</div>
            <div class="col">点赞数: ${image.likes.toLocaleString()}</div>
          </div>
          <p class="card-text mt-3">图片尺寸: ${image.imageWidth} × ${image.imageHeight}</p>
        </div>
      </div>
    `;
    document.getElementById('imageDetails').innerHTML = detailsHtml;
  } catch (error) {
    document.getElementById('imageDetails').innerHTML = `<p>加载失败: ${error.message}</p>`;
  }
}

// 页面加载时执行
renderImageDetails();

关键说明

  • 代码兼容两种URL格式:原始查询参数格式和你想要的哈希路径格式
  • 通过id参数直接调用Pixabay API可精准获取单张图片的完整数据
  • 添加了异常处理,避免网络错误或无效ID导致页面空白

内容的提问来源于stack exchange,提问作者Himansu Kumar Nayak

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.05 17:35:00