Difference between returning ModelAndView in ajax

2019-08-11 01:16发布

问题:

Why when i return a ModelAndView in a call ajax it works and display the jsp page normally but when when i return it into a map with other object it doesn't work.

First case which work:

@RequestMapping(value="/searchlostcard") 
public  @ResponseBody
ModelAndView searchlostcard() {             
    [...]   
return new ModelAndView("search/results","cardlist", listlostcard); ; 
}

My ajax call

[...]
success : function(responce) {              
    $('#page_grid').html(responce);
}

Second case which doesn't work:

@RequestMapping(value="/searchlostcard") 
public  @ResponseBody
Map<String, Object> searchlostcard() {          
    [...]   
    ModelAndView MaV = new ModelAndView("search/results","cardlist", listlostcard);

    Map<String, Object> modelino = new HashMap<String, Object>();

    modelino.put("taille", listlostcard.size());
    modelino.put("vue", MaV);

    return modelino ; 

}

My ajax call

[...]
success : function(responce) {          
     $('#page_grid').html(responce['vue']);
}

回答1:

When you return a ModelAndView then Spring MVC renders a view and returns that rendered view, regardless of the @ResponseBody annotation. That is HTML (provided your view is HTML) is returned to the client.

Whereas when you return a Map and have an @ResponseBody annotation then Spring returns the serialized object (e.g. a JSON string representing the map). The view that is referenced by your MaV variable is not rendered in this case. That is you don't have any HTML returned to the client.



回答2:

You apparently don't understand the concept of @ResponseBody. It does not trigger a JSP (or other view technology), but returns the Object itself, rendered to JSON, XML or whatever content negotiation is set up for.

You could try removing the annotation and see if it works.