【问题标题】:How to show response from AJAX call to Spring controller method?如何显示 AJAX 调用对 Spring 控制器方法的响应?
【发布时间】:2019-10-27 21:13:51
【问题描述】:

如何显示对返回 HTML 的 Spring MVC 控制器的调用响应?在我的 Javascript 代码中,我对我的 Spring 控制器进行了 (GET) 调用。据我所知,调用的响应是 HTML。我想我需要用 Javascript 替换 'alert(response)' 来显示 html。

我的 Javascript 代码:

     $('#parcelsTable').on( 'click', 'tr', function () {
         var data = table.row( this ).data();

         $.ajax({
             url:"/parcel/showFormForUpdate",
             type:"GET",
             data:{parcelId:data.parcelId},
             success: function(response){
                alert(response) 
             }
         });
     } );

我在 Spring 中的控制器代码:

@GetMapping("/showFormForUpdate")
public String showFormForUpdate(@RequestParam("parcelId") int theId, Model theModel) {

    Parcel theParcel = parcelService.findById(theId);
    theModel.addAttribute("theParcel", theParcel);
    return "parcel-form";
}

这里的“parcel-form”是一个模板的名称。

【问题讨论】:

标签: javascript ajax spring-mvc


【解决方案1】:
     $('#parcelsTable').on( 'click', 'tr', function () {
         var data = table.row( this ).data();

         $.ajax({
             url:"/parcel/showFormForUpdate",
             type:"GET",
             data:{parcelId:data.parcelId},
             success: function(response){
                $.get(response.html, function(data, status){
                $("#ID").html(data);
                }); 
             }
         });
     } );

response.html 是您想要在获取请求成功时显示的页面。只需对 response.html 文件或任何模板文件发出 get 请求,然后将此文件放在您要显示的任何 div 中。

希望它有效

【讨论】:

  • 响应的内容是一个 HTML 文档,从我的 Spring 控制器返回。我想被重定向到包含响应的新页面。 $(#ID) 指的是哪里?
  • 很遗憾,您的解决方案弄乱了我的页面,因为表格的内容不再显示。
  • 只是为了检查我是否正确理解了您的解决方案...我需要创建一个文件,以便可以插入响应中的 html,然后重定向到该文件?
  • 是的...您只需将该 html 内容文件插入具有该 ID 的任何 div 中。否则您可以简单地重定向到 response.html
猜你喜欢
  • 2011-06-22
  • 2014-01-15
  • 2016-06-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-05-16
  • 1970-01-01
  • 2021-05-22
相关资源
最近更新 更多