tags:

views:

1268

answers:

2

Hi, I am trying to call a Spring MVC controller through an ajax call from JavaScript method.The javascript method is using Prototype library to make the ajax call.The controller throws JSP as output. I am able to hit the controller as i can see in the log messages however the response seems to get lost.What could be the issue.Here is the code....

 <script language="JavaScript" src="prototype-1.6.0.3.js"></script>


function submitNewAjxCall() {
alert('test');
new Ajax.Request('SimpleApp/home.htm',
{
method:'post',
parameters: $('formId').serialize(true),
onComplete: showresult
});
}

    function showresult(resultdata) {<br>
    alert(resultdata.responseText); ****//this method is not called.....****<br>
    }<br>



home.htm point to this controller
public ModelAndView handleRequest(HttpServletRequest request,
HttpServletResponse response) throws Exception {
System.out.println("HomeController : " + ++i);
return new ModelAndView("home");
} --- this throws home.jsp

Thanks for your help.

A: 

One solution i found it... http://perfectionlabstips.wordpress.com/2009/01/07/serving-json-data-with-spring-mvc-2/ its more of a work around then a fix ....

Rajat
+1  A: 

Check with Firebug (Net tab) if you get the Ajax response and and see what its content is. Maybe it makes sense to not return the whole HTML page but a JavaScript specific JSON object that's telling something about what the controller just did. Maybe add a ajax GET property to your controller where you just output plain JSON to the Response Body instead of returning the ModelAndView. Try to use onSucess in Prototype. Maybe that might work then

function submitNewAjxCall()
{
 new Ajax.Request('SimpleApp/home.htm?ajax=true',
 {
  method: 'post',
  parameters: $('formId').serialize(true),
  onComplete: function(transport)
  {
   alert(transport.responseText);
  }
 });
}

Edit: To write JSON directly (e.g. using Flexjson as the serializer) you can use this in your (annotated) Spring controller:

 @RequestMapping(value = "/dosomething.do", method = RequestMethod.GET, params = "ajax=true")
 public void getByName(
   @RequestParam(value = "name", required = true) String name,
   HttpServletResponse response
   )
 {
  response.setContentType("application/json");
  try
  {
   OutputStreamWriter os = new OutputStreamWriter(response.getOutputStream());
   List<DomainObjects> result = this.domainObjectService.getByName(name);
   String data = new JSONSerializer().serialize(result);
   os.write(data);
   os.flush();
   os.close();
  } catch (IOException e)
  {
   log.fatal(e);
  }
 }
Daff
In Spring Controller we need to write output back to the output stream directly as JSON.We will have to extend existing controls and provide this functionality.
Rajat
I wrote a basic JSON controller using Flexjson as the encoder. I added an example for the spring controller, too.
Daff