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

Google Books API调用无控制台输出,图书查询功能失效求助

图书查询项目无结果问题排查与修复

问题描述

开发一个基于单选框+搜索栏的图书信息查询工具,设置了ISBN10、标题、作者三个单选选项,计划按选中类别搜索图书,但测试时无任何结果,控制台看不到Google Books API的返回内容,调整后仍未解决。

现有代码

JavaScript代码

$(document).ready(function() {
  $("#searchform").submit(function() {
    const searchTerm = $("#titleName").val();
    const selection = $('input[name="search"]:checked').val();

    if (searchTerm === '') {
      alert("搜索栏不能为空");
    } else {
      switch (selection) {
        case 'ISBN10':
          if (validIsbn(searchTerm)) {
            $.get(`https://www.googleapis.com/books/v1/volumes?q=${searchTerm}`, function(response) {
              console.log(response);
            }).fail(function() {
              alert('错误:无法获取图书信息。');
            });
          } else {
            alert("ISBN10格式不正确");
          }
          break;

        case 'title':
          if (validIsbn(searchTerm)) {
            alert("输入了ISBN10格式内容,请输入正确的标题。");
          } else {
            $.get(`https://www.googleapis.com/books/v1/volumes?q=${searchTerm}`, function(response) {
              console.log(response);
            }).fail(function() {
              alert('错误:无法获取图书信息。');
            });
          }
          break;

        case 'author':
          if (validIsbn(searchTerm)) {
            alert("输入了ISBN10格式内容,请输入正确的作者名。");
          } else {
            $.get(`https://www.googleapis.com/books/v1/volumes?q=${searchTerm}`, function(response) {
              console.log(response);
            }).fail(function() {
              alert('错误:无法获取图书信息。');
            });
          }
          break;

        default:
          alert('请选择搜索类别。');
          break;
      }
    }
    return false;
  });
});

function validIsbn(ISBN) {
  ISBN = ISBN.replace(/[-\s]/g, "");

  if (ISBN.length !== 10) {
    return false;
  }

  if (!/^\d+$/.test(ISBN)) {
    return false;
  }

  return true;
}

HTML代码

<section class="searchBar">
    <fieldset id="searchform">
        <label for="titleName"> </label><br>
        <input type="text" id="titleName" name="titleName" placeholder="搜索书名、ISBN或作者"><br>
        <label for="opTitle">标题</label>
        <input type="radio" id="opTitle" value="title" name="search" checked>
        <label for="opISBN">ISBN10</label>
        <input type="radio" id="opISBN" value="ISBN10" name="search"><br>
        <label for="opAuthour">作者</label>
        <input type="radio" id="opAuthour" value="author" name="search">
        <button type="submit" id="Searchsubmit" name="Searchsubmit">搜索</button><br>
    </fieldset>
</section>

问题原因与修复方案

1. Google Books API搜索参数错误(核心问题)

当前所有请求都直接用q=${searchTerm},API无法识别你要按ISBN、标题还是作者搜索,导致返回结果为空或不符合预期。需要添加API指定的限定符:

  • ISBN搜索:isbn:${searchTerm}
  • 标题搜索:intitle:${searchTerm}
  • 作者搜索:inauthor:${searchTerm}

2. 标题/作者搜索的ISBN校验逻辑错误

标题和作者允许包含数字(比如书名《1984》),但当前代码会把这类输入误判为ISBN并阻止搜索,需移除标题、作者分支里的ISBN校验逻辑。

3. HTML拼写错误(非核心但建议修正)

作者单选框的id="opAuthour"拼写错误,应为id="opAuthor",不影响功能但符合规范。

4. 表单提交处理优化(可选)

用event.preventDefault()替代return false,更符合现代JS事件处理规范。

修正后的代码

修正后的JavaScript

$(document).ready(function() {
  $("#searchform").submit(function(e) {
    // 阻止表单默认提交行为
    e.preventDefault();
    
    const searchTerm = $("#titleName").val().trim();
    const selection = $('input[name="search"]:checked').val();

    if (!searchTerm) {
      alert("搜索栏不能为空");
      return;
    }

    let apiUrl = '';
    switch (selection) {
      case 'ISBN10':
        if (validIsbn(searchTerm)) {
          apiUrl = `https://www.googleapis.com/books/v1/volumes?q=isbn:${searchTerm}`;
        } else {
          alert("ISBN10格式不正确");
          return;
        }
        break;

      case 'title':
        apiUrl = `https://www.googleapis.com/books/v1/volumes?q=intitle:${searchTerm}`;
        break;

      case 'author':
        apiUrl = `https://www.googleapis.com/books/v1/volumes?q=inauthor:${searchTerm}`;
        break;

      default:
        alert('请选择搜索类别。');
        return;
    }

    // 统一发起API请求
    $.get(apiUrl, function(response) {
      console.log(response);
      // 这里可以添加渲染图书信息的逻辑
    }).fail(function(xhr, status, error) {
      console.error('API请求失败:', status, error);
      alert('错误:无法获取图书信息,请检查网络或搜索内容。');
    });
  });
});

function validIsbn(ISBN) {
  ISBN = ISBN.replace(/[-\s]/g, "");

  if (ISBN.length !== 10) {
    return false;
  }

  if (!/^\d+$/.test(ISBN)) {
    return false;
  }

  // 可选:添加ISBN10校验位验证,提高准确性
  let sum = 0;
  for (let i = 0; i < 9; i++) {
    sum += parseInt(ISBN[i]) * (10 - i);
  }
  const checkDigit = 11 - (sum % 11);
  const lastChar = ISBN[9].toUpperCase();
  return (checkDigit === 11 && lastChar === 'X') || (checkDigit === parseInt(lastChar));
}

修正后的HTML

<section class="searchBar">
    <fieldset id="searchform">
        <label for="titleName"> </label><br>
        <input type="text" id="titleName" name="titleName" placeholder="搜索书名、ISBN或作者"><br>
        <label for="opTitle">标题</label>
        <input type="radio" id="opTitle" value="title" name="search" checked>
        <label for="opISBN">ISBN10</label>
        <input type="radio" id="opISBN" value="ISBN10" name="search"><br>
        <label for="opAuthor">作者</label>
        <input type="radio" id="opAuthor" value="author" name="search">
        <button type="submit" id="Searchsubmit" name="Searchsubmit">搜索</button><br>
    </fieldset>
</section>

测试建议

  1. 打开浏览器控制台(F12),查看API请求的状态和返回内容;
  2. 测试ISBN10搜索:输入有效的10位ISBN(比如0451524934);
  3. 测试标题搜索:输入1984或哈利波特;
  4. 测试作者搜索:输入J.K.罗琳或George Orwell。

内容的提问来源于stack exchange,提问作者HappyTears

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 21:55:05