How to pass parameters to controller using ajax and javascript? -
i trying delete item shopping cart using ajax javascript, have trouble passing parameters controller. parameters null in controller.
my javascript code shows below:
function removerow(itemid, rowid){ if (xmlhttp == null) { alert("your browser not support ajax!"); return; } var query = "action=remove&item=" + itemid; /* alert(query); */ xmlhttp.onreadystatechange = function statechanged() { if (xmlhttp.readystate == 4) { var row = document.getelementbyid(rowid); row.parentnode.removechild(row); } }; xmlhttp.open("get", "addto.htm", true); xmlhttp.setrequestheader("content-type", "application/x-www-form-urlencoded"); xmlhttp.send(query); return false; /* var row = document.getelementbyid(rowid); row.parentnode.removechild(row); */
}
my controller code shows below:
@controller @requestmapping("/addto.htm") public class addtocontroller{ @requestmapping(method=requestmethod.get) protected modelandview handlerequestinternal(httpservletrequest request, httpservletresponse response) throws exception { httpsession session = request.getsession(); string action = request.getparameter("action"); system.out.println(action); modelandview mv = new modelandview(); arraylist<item> cart; if(action.equals("remove")){ system.out.println("cart size is" + cart.size()); long itemid = long.parselong(request.getparameter("item")); itemdao itemdao= new itemdao(); item item = itemdao.get(itemid); cart.remove(item); system.out.println(cart.size()); } return mv; } }
the action , item null in controller.
can problem?
you're sending request, add parameters query after url:
xmlhttp.open("get", "addto.htm?" + query, true);
and pass in null (rather query string) when calling .send method:
xmlhttp.send(null);
also, "application/x-www-form-urlencoded" header used when you're sending serialised parameters using post, remove xmlhttp.setrequestheader
line.
more info: https://developer.mozilla.org/en-us/docs/ajax/getting_started
Comments
Post a Comment