【问题标题】:Spring Ajax Cannot find Controller handlerSpring Ajax 找不到控制器处理程序
【发布时间】:2021-01-13 22:01:33
【问题描述】:

我是使用 AJAX 编程的新手。目前,我收到一个 404 错误代码,但我不太确定出了什么问题,如果有人能提供帮助,我将不胜感激。我正在尝试使用用户输入来访问数据库。我正在使用 AJAX 向控制器发送数据,但控制器没有接收到 AJAX 请求。如果有人可以提供帮助,我将不胜感激。

错误代码是:

jquery.min.js:6 GET http://localhost:8080/GCSE/student_report/7days_report/?username=v 404

这是我的 ajax 代码

 $(document).ready(function(){
 $("#username").keyup(function(){
     console.log($("#username").val());
     $.ajax({
     type: "GET",
     url:
    "/GCSE/student_report/7days_report/?username="+$("#username").val(),
     success: function(result){
     $("#name").html(result);
     }
     });
    });
 });

这是控制器代码

@RequestMapping(value = "/GCSE/student_report/7days_report/{username}")
public ModelAndView getGCSEReportBy_JSON() {
 Report GCSE = ps.getReportsWithUsernamePrefix(username);
 return new ModelAndView("index", "data", GCSE);
}

PS 服务代码

    @Autowired
private ReportRepository rrRepo;
public Iterable<Report> getAllReports(){
    return rrRepo.findAll();
}

杰夫干杯

【问题讨论】:

    标签: ajax spring controller


    【解决方案1】:

    Ajax 中的 URL 应该是:

    "/GCSE/student_report/7days_report/" + $("#username").val()

    在方法中,您可以使用方法签名提取用户名

    @RequestMapping(value = "/GCSE/student_report/7days_report/{username}")
    public ModelAndView getGCSEReportBy_JSON(@PathVariable String username)
    

    如果你想使用你创建的链接,那么方法应该是

    @RequestMapping(value = "/GCSE/student_report/7days_report")
    public ModelAndView getGCSEReportBy_JSON(@RequestParam String username)
    

    @PathVariable 从 URL 路径中提取变量,其中变量使用 {} 和路径定义。 @RequestParam 提取 URL 中 ? 之后定义的变量。

    【讨论】:

    • 感谢您的回复,我现在运行时收到错误代码500。我将第一部分更改为您所说的内容并使用了路径变量。
    • 错误代码 500 是内部服务器错误。检查弹簧控制台日志以获取信息。我不确定您使用哪个模板引擎,例如 thymeleaf 或类似引擎,但可能返回空的 ModelAndView 对象会导致错误。
    • 谢谢@Boris,我现在已经在我的modelAndView中添加了我的参数,但我仍然收到错误,我已经用更新的代码更新了解决方案。
    • @JeffereyJohnSmith,如果您可以将收到的错误日志粘贴到某个地方,那么我可以看一下,也许我可以看到问题所在。
    • 嘿,原来我只是个白痴,它找不到返回视图,所以它找到了控制器,所以你的代码有效。谢谢你的帮助,我会标记为答案:)
    猜你喜欢
    • 2019-03-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-12
    相关资源
    最近更新 更多