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

时间:2020-05-06 01:30:50

标签: javascript java html ajax spring-boot

我正在编写一个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"/>

1 个答案:

答案 0 :(得分:1)

我将添加一个新方法,该方法仅返回供您使用的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)
})