简体   繁体   中英

How to show response from AJAX call to Spring controller method?

How do I display the response of a call to a Spring MVC Controller returning HTML? In my Javascript code I make a (GET) call to my Spring Controller. From what I can make is that the response from the call is HTML. I guess I need to replace 'alert(response)' with Javascript to display the html.

My Javascript code:

     $('#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) 
             }
         });
     } );

My controller code in Spring:

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

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

Here "parcel-form" is the name of a template.

     $('#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 is the page you want to show on the success of get request. Just make a get request to the response.html file or any template file and put this file in any div where you want to show it.

Hope that it works

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM