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
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
You don't get a
ModelAndView
object in AJAX. Spring usesHandlerMethodReturnValueHandler
instances to handle your handler method's return value. ForModelAndView
, it usesModelAndViewResolverMethodReturnValueHandler
. For@ResponseBody
, it usesRequestResponseBodyMethodProcessor
. These are checked in a specific order and the one forModelAndView
has higher priority. Therefore, when you return aModelAndView
, Spring will add the model attributes to the fullModel
and then resolve your view name to, probably, ajsp
and write the response from thatjsp
, 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.