Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning ModelAndView in ajax spring mvc

Hi am using spring mvc + ajax. I made a ajax call by passing a userid. And everything goes fine successfully returned to ajax but when i alert the response its simple showing the html page code. Please help me to sort out this prob. I think i didnt coded my ajax well.Help me to in correct way

Controller code:

  public @ResponseBody ModelAndView abc(HttpServletRequest httpServletRequest,
        HttpSession session, ModelMap map){

      ModelAndView modelAndView = new ModelAndView("abcd.page",
                "commandName", object);
           return modelAndView;

Ajax code :

     $(".userDetails").click(function() {
            alert("clicked");
        var userId=$(this).parent().parent(). parent().find(".userId"). 
                       text().trim();
            alert("userId :"+userId);
            $.ajax({

            url : 'ABC.htm',
            type : 'GET',
            data: {userId:userId},
            beforeSend: function(xhr) {  
                xhr.setRequestHeader("Accept", "application/json");  
                xhr.setRequestHeader("Content-Type", "application/json");  
            },  
            success : function(response) {
                alert("success");
                alert(response);
            },
            error : function(res) {
                alert("error");
            },

        });

            return false;
        });

The output for the alert(response); is enter image description here

EDIT: Can any one please tell why ajax giving html content on success... After many changes i made getting the same alert.

Edited Again : I think i dont have any problem in controller. Please suggest me solution to code my ajax correctly. It seems error here. How to get a ModelAndView object in ajax

like image 561
Monicka Akilan Avatar asked Nov 14 '13 11:11

Monicka Akilan


1 Answers

You don't get a ModelAndView object in AJAX. Spring uses HandlerMethodReturnValueHandler instances to handle your handler method's return value. For ModelAndView, it uses ModelAndViewResolverMethodReturnValueHandler. For @ResponseBody, it uses RequestResponseBodyMethodProcessor. These are checked in a specific order and the one for ModelAndView has higher priority. Therefore, when you return a ModelAndView, Spring will add the model attributes to the full Model and then resolve your view name to, probably, a jsp and write the response from that jsp, giving you some HTML. Since AJAX just sees the response from the request, it will see HTML.

If you want to return JSON, don't return a ModelAndView, return the model object directly or write JSON directly to the response yourself.

like image 54
Sotirios Delimanolis Avatar answered Sep 19 '22 06:09

Sotirios Delimanolis