javascript - 从网站上的 JavaScript 脚本调用 Java SpringBoot 服务器方法
问题描述
我正在我的网站上制作一个子菜单,它有 5 个选项,每个选项都是游戏的名称。当用户选择一个选项时,我希望我的服务器打印用户选择的游戏名称。这里我有两个问题:
- 我不知道为什么在单击子菜单选项后,我总是得到第一个游戏名称。
- 我不知道如何从 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";
}
解决方案
您的第一个问题在于您的点击事件侦听器。因此,每当您单击 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
});
推荐阅读
- php - 为什么 PHP 会为我的表格代码生成乱码 HTML?
- python - 为什么最后一个元素反映了非负解的数量?
- apache - 使用 Apache 2 在同一 IP 上为我的站点部署管理面板
- c# - 删除和排序 Usings 在 Visual Studio 2019 中不起作用
- javascript - 生日蛋糕蜡烛-hackerrank
- node.js - 如何在没有 API 的情况下访问 Google Classroom?
- google-cloud-platform - 无法在 Dataflow 中查看 beam.combiners.Count.PerElement() 的输出
- sql - 执行 UNNEST、INNER JOIN 和 ARRAY_AGG 作为 UPDATE 查询的一部分
- python - PyGame 不稳定
- android - ionic cordova run android 在无效的 adb 位置失败?