简体   繁体   中英

Ajax POST call to Spring MVC

This question is follow up of Returning ModelAndView in ajax spring mvc

As the only answer says that we need to return json from Controller not ModelAndView. So the question is

  1. what can be done to return ModelAndView ?
  2. How the page will be rendered:-
    • will it have to be handled in success section of ajax call
    • Or Spring Controller will return the page as usually it does in Spring MVC
  3. How the post data from ajax can be read in Controller.

Update 1: As explained, I tried example. here is my code.

@Controller
public class AppController 
{

@RequestMapping(value="/greeting",method=RequestMethod.POST)
@ResponseBody
public ModelAndView getGreeting(@RequestBody String json) throws IOException
{
    JSONObject inputjsonObject = new JSONObject(json);
    String name = inputjsonObject.getString("name");
    ModelAndView modelAndView = new ModelAndView();
    String result = "Hi "+name;
    modelAndView.addObject("testdata", result);
    modelAndView.addObject("user", getPrincipal());
    modelAndView.setViewName("greetingHtmlPage");
    return modelAndView;
}
// other stuff
}

In above controller method i can get data sucessfully. This method is called from a javascript on home.html . Below is javascript function

 function callGreeting(){
            var nameData={
                    name :  document.getElementById("name").value
                }
            var dataInJson = JSON.stringify(nameData);
            var csrf_token = document.getElementById("token").value;
            $.ajax({
            type: 'POST',
            url: "greeting",
            data: dataInJson,
            cache:false,
            beforeSend: function(xhr) { 
                xhr.setRequestHeader('X-CSRF-Token', csrf_token);
                xhr.setRequestHeader("Accept", "application/json");  
                xhr.setRequestHeader("Content-Type", "application/json");  
            },
           success: function (response) {
               document.open();
                document.write(response);
                document.close();
            },
            error: function (data) {
                alert("failed response");
            }
        }); }

I have the page rendered successfully. But the url of application does not changes from AjaxSpringMVC:8080/home to AjaxSpringMVC:8080/greeting even after new page was loaded. This happens by itself in Spring MVC if using without Ajax.

what can be done to return ModelAndView ?

You can return ModelAndView As usual:

public ModelAndView returnView( Model model ) {
    model.addAttribute( "myStaff", "my staff as string" );

    return new ModelAndView( "myView" );
}

How the page will be rendered:

You control how it is rendered, . When you return ModelAndView , the response has an HTML page. After the Ajax call, you can do $("#container").html(response) or something like that to display the HTML page wherever you want.

In other words, you get a whole html page of content from the controller.

However, I highly recommend that you just return json object and update your view with the json object. Ajax is mostly used to create good user experience by updating part of the view asynchronously, so getting a whole page with Ajax does not make sense to me.

How the post data from ajax can be read in Controller.

There are many ways, I like to send json body directly to controller

@ResponseBody
@RequestMapping(value = "/saveObj", method = RequestMethod.POST, consumes = "application/json")
public String saveObj(Model model, @RequestBody MyObj myObj) {
    // do staff..
}

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