如何在网站上显示AJAX响应数据

问题
我正在编写一个Spring Boot应用程序,其中有一个带有子菜单的网站,其中包含多个计算机游戏。当我单击此子菜单中的某个位置时,我希望服务器发送该游戏的图像(按图像表示图像的路径)作为响应,并在响应返回到我在网站上的JS之后,在网站上显示。我已经完成的工作是向服务器发送请求,然后根据请求数据选择图像。我不知道如何发送回复并在我的网站上使用它。
这是我的代码:
Java:

@RequestMapping("/change-game")
public String changeGame(HttpServletRequest request, @RequestBody GameData data){
    File file;
    String game = data.getName();
    switch (game) {
        //some code which actually works. I removed it to save space
    }
    request.setAttribute("gameIcon", file);
    return "index";
}

我正在编写一个Spring Boot应用程序,其中有一个带有子菜单的网站,其中包含多个计算机游戏。当我单击此子菜单中的某个位置时,我希望服务器发送该游戏的图像(按图像表示图像的路径)作为响应,并在响应返回到我在网站上的JS之后,在网站上显示。我已经完成的工作是向服务器发送请求,然后根据请求数据选择图像。我不知道如何发送回复并在我的网站上使用它。
这是我的代码:
Java:

@RequestMapping("/change-game")
public String changeGame(HttpServletRequest request, @RequestBody GameData data){
    File file;
    String game = data.getName();
    switch (game) {
        //some code which actually works. I removed it to save space
    }
    request.setAttribute("gameIcon", file);
    return "index";
}

JavaScript:

$("#selectGameSubmenu li").click(function(e){
    e.preventDefault();
    var option = $(this).data("option");
    console.log(option + " " + JSON.stringify({"option": option}));
    $.ajax({
        type: "POST",
        url: "http://localhost:8080/change-game",
        data: JSON.stringify({name: option}),
        contentType: "application/json; charset=utf-8",
        dataType: "json"
    });
});

HTML:

 <img src="${gameIcon}" alt="${altGameIcon}"
             style="width:100px;height:100px" class="gameLogoCenter"/>

答:
我将添加一个新方法,该方法仅返回要使用的AJAX调用的图像路径。
例如

@ResponseBody
@PostMapping("/change-game-icon")
public String changeGameIcon(@RequestBody GameData data) {
    File file;
    String game = data.getName();
    switch (game) {
        //some code which actually works. I removed it to save space
    }
    return file.toString();
}

在你的JS里

$.ajax({
  url: '/change-game-icon',
  method: 'post', // or "type" if your jQuery is really old
  data: JSON.stringify({name: option}),
  dataType: 'text',
  contentType: 'application/json'
}).done(iconPath => {
  $('img.gameLogoCenter').prop('src', iconPath)
})

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值