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 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With