I'm having a problem with Spring MVC and Ajax. I'm trying to send a javascript list to my Spring Controller, but I can't. I've to do a search and I need to send a list with some parameters.
-
1May be helpful if you provide a short example of your javascript, the ajax call and how do you know its not working? Are you getting a javascript error or an error on the server side or both?km1– km12012-07-19 03:12:17 +00:00Commented Jul 19, 2012 at 3:12
-
blog.springsource.com/2010/01/25/…NimChimpsky– NimChimpsky2012-07-19 08:26:56 +00:00Commented Jul 19, 2012 at 8:26
Add a comment
|
3 Answers
You will have to convert to the list to json if you sending via ajax, this From the spring blog itself :
$("#account").submit(function() {
var account = $(this).serializeObject();
$.postJSON("account", account, function(data) {
$("#assignedId").val(data.id);
showPopup();
});
return false;
});
@RequestMapping(method=RequestMethod.POST)
public @ResponseBody Map<String, ? extends Object> create(@RequestBody Account account, HttpServletResponse response) {
Set<ConstraintViolation<Account>> failures = validator.validate(account);
if (!failures.isEmpty()) {
response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
return validationMessages(failures);
} else {
accounts.put(account.assignId(), account);
return Collections.singletonMap("id", account.getId());
}
}
Comments
This answer in SO might help
jquery ajax on client side
$.ajax({
type: "POST",
url: "submit",
data:JSON.stringify(detailsArr),
success: function(html){
alert( "Submitted");
}
});
and on server side
@RequestMapping(value = "/search", method=RequestMethod.POST)
public String yourMethod(@RequestBody String body){
//convert body to array using JSONLib, FlexJSON or Gson
}