java - How to correctly handle this AJAX request that send an array to a Spring MVC controller method? Why it can't work? -
i pretty new in spring mvc , have following problem trying handle ajax request send array of int controller method.
so have following situation. have jquery function:
// global , initiazilized function: var checkedrowlist = new array(); // other code inizialized checkedrowlist array here ............................................... ............................................... ............................................... $('#validabutton').click(function() { alert("validazione"); alert("checked rows: " + checkedrowlist.length); alert(checkedrowlist[0]); $.ajax({ type: "post", data: {'checkedrowlist' : checkedrowlist}, url: "validaprogetti" }).done(function(response) { alert("success"); }).error(function(xhr) { alert("error"); manageerror(xhr); }); });
so checkedrowlist correctly initizialized (i checked it) , use ajax() function send toward validaprogetti resource using post request.
then controller class have method have handle previous request:
@requestmapping(value = "validaprogetti", method=requestmethod.post) public string validaprogetti(@requestparam list<integer> checkedrowlist, model model, httpservletrequest request) { system.out.println("numero progetti da validare: " + checkedrowlist); return "blablabla"; }
as can see handle http post request toward validaprogetti resource. , inside have specify requestparam list checkedrowlist retry array passed ajax request.
but don't work because when ajax request performed don't enter validaprogetti() method , shown alert("success"); popup.
why? missing? how can fix situation?
as see missed 2 things. first 1 in spring web mvc controller. don't pass requestparam
requestbody
.
@requestmapping(value = "validaprogetti", method=requestmethod.post) public @responsebody string validaprogetti(@requestbody list<integer> checkedrowlist) { system.out.println("numero progetti da validare: " + checkedrowlist); return "blablabla"; }
the second 1 related ajax request. should send javascript array formatted json. done via function json.stringify()
, converts js
value json
.
$('#validabutton').click(function() { alert("validazione"); alert("checked rows: " + checkedrowlist.length); alert(checkedrowlist[0]); $.ajax({ type: "post", data: json.stringify(checkedrowlist), url: "validaprogetti", contenttype:"application/json" }).done(function(response) { alert("success"); }).error(function(xhr) { alert("error"); manageerror(xhr); }); });
Comments
Post a Comment