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

SpringBoot @RequestParam接口与JQuery $.getJSON传参无响应问题求助

错误排查及修复方案

核心错误点

  • 路由与参数类型不匹配:后端/books-genre接口接收的是查询参数genre2,不是路径变量,你前端把参数拼接在URL路径里的写法/books-genre/xxx会直接404,后端无法匹配路由。
  • 表单默认提交行为干扰:你用了type="submit"的按钮,点击后会触发表单默认提交刷新页面,AJAX请求未完成就被中断,看不到执行效果。
  • 元素ID取值错误:页面输入框的ID是genre,不存在ID为genre2的元素,$('#genre2').val()只能拿到undefined,无法传递正确参数。
  • 手动写的测试请求语法错误:你尝试的$.get(/books-genre, {genre2 : drama})写法中,URL路径没有加引号变为字符串,drama如果是常量也没有加引号,语法错误导致请求无法执行。

修复步骤

1. 修改表单按钮

把提交按钮类型改为button,阻止默认表单刷新行为:

<input type="button" onclick="findBooksByGenre()" value="Submit">

2. 修正前端AJAX逻辑

function findBooksByGenre () {
    // 正确获取输入框的值
    const genreVal = document.getElementById("genre").value;
    // 按照后端要求传递查询参数,key为genre2
    $.getJSON('/books-genre', {genre2: genreVal})
    .done(function (books2) {
        alert(books2.length);
        // 先清空旧的表格内容,避免重复追加
        $('tbody').empty();
        books2.forEach(function (book2) {
            const coment = book2.comments.length;
            const cond = coment != 0 ? coment : 'no comments';
            $('tbody').append(`
                <tr>
                    <td>${book2.id}</td>
                    <td>${book2.name}</td>
                    <td>${book2.author.name}</td>
                    <td>${book2.genre.name}</td>
                    <td> ${cond}
                    <a href="comments/?bookId=${book2.id}">view</a>
                    </td>
                </tr>
            `)
        });
    })
    // 新增错误回调,方便后续排查其他问题
    .fail(function (xhr) {
        console.error('请求失败,状态码:', xhr.status, '错误信息:', xhr.responseText);
    })
};

3. 可选:如果要使用路径变量写法

如果你想保留把参数拼在URL里的写法,需要同步修改后端接口:

@GetMapping(value = "/books-genre/{genre2}")
public List<BookDto> findBooksByGenre(@PathVariable(name = "genre2") String genre) {
    System.err.println(genre);
    List<Book> books = BookService.findBooksByGenre(genre);
    return bookDtoConverter.booksToDto(books);
}

然后前端请求写法改为$.getJSON('/books-genre/' + genreVal)即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.23 17:36:01