首页 > 解决方案 > 从网站上的 JavaScript 脚本调用 Java SpringBoot 服务器方法

问题描述

我正在我的网站上制作一个子菜单,它有 5 个选项,每个选项都是游戏的名称。当用户选择一个选项时,我希望我的服务器打印用户选择的游戏名称。这里我有两个问题:

  1. 我不知道为什么在单击子菜单选项后,我总是得到第一个游戏名称。
  2. 我不知道如何从 JS 向作为服务器的 Spring Boot 应用程序发送请求。
    你能帮助我吗?这是我的代码:
<ul class="collapse list-unstyled" id="selectGameSubmenu">
    <li data-option="League of Legends">
        <a href="#"><img src="../../../static/images/league_of_legends/leagueoflegends_icon.png"
                         alt="" style="width:16px;height:16px"> League of Legends</a>
    </li>
    <li data-option="Teamfight Tactics">
        <a href="#"><img src="../../../static/images/teamfight_tactics/teamfighttactics_icon.png"
                         alt="" style="width:16px;height:16px"> Teamfight Tactics</a>
    </li>
    <li data-option="Legends of Runterra">
        <a href="#"><img src="../../../static/images/legends_of_runterra/legendsofruneterra_icon.png"
                         alt="" style="width:16px;height:16px"> Leagends of Runterra</a>
    </li>
    <li data-option="Valorant">
        <a href="#"><img src="../../../static/images/valorant/valorant_icon.png"
                         alt="" style="width:16px;height:16px"> Valorant</a>
    </li>
    <li data-option="Counter Strike">
        <a href="#"><img src="../../../static/images/counter_strike/counterstrike_icon.png"
                         alt="" style="width:16px;height:16px"> Counter Strike</a>
    </li>
</ul>
$("#selectGameSubmenu").click(function(e){
    e.preventDefault();
    var option = $("#selectGameSubmenu li").data("option");
    console.log(option);
});
@PostMapping("/change-game")
public String changeGame(@RequestParam String game){
    System.out.println("Selected option: " + game);
    return "index";
}

标签: javascriptjavahtmljqueryspring-boot

解决方案


您的第一个问题在于您的点击事件侦听器。因此,每当您单击 ul 元素时,它都会触发,但是当您定义这样一个选择器$("#selectGameSubmenu li") 时,它将始终返回您的第一个子ul元素is League of Legends

要修复它,您应该对其进行一些修改。首先,不要在你的中添加事件监听器,ul 你应该在你的中添加一个事件监听li器,然后通过 using 获取特定的点击项$(this),输出应该是这样的:

$("li").click(function (e) {
  e.preventDefault();
  var option = $(this).data('option');
  console.log(option);
});

您的第二个问题很简单,对于后端和前端应用程序之间的通信,您应该使用类似ajax. 请求将ajax有助于在应用程序之间检索和发送数据。有关它的更多信息,您可以阅读以下任一文章:JQuery 文档站点点免费代码营

您的请求将是这样的:

$.ajax({
  type: "POST",
  url: url, // Your end point address 
  data: data, // Your data
  success: success // Your actions after data send successfully 
});

推荐阅读