[英]How to pass parameters to controller using ajax and javascript?
I am trying to delete an item from shopping cart using Ajax with javascript, but I have trouble passing parameters to the controller.我正在尝试使用带有 javascript 的 Ajax 从购物车中删除一个项目,但我无法将参数传递给控制器。 The parameters are null in controller.控制器中的参数为空。
My javascript code shows as below:我的 javascript 代码如下所示:
function removeRow(itemId, rowID){
if (xmlHttp == null)
{
alert("Your browser does 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 as 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 and item are null in the controller.控制器中的操作和项目为空。
Can anyone help with this problem?任何人都可以帮助解决这个问题吗?
You're sending a GET request, so add the parameters as a query after your URL:您正在发送 GET 请求,因此在您的 URL 后添加参数作为查询:
xmlHttp.open("GET", "addTo.htm?" + query, true);
and pass in null (rather than your query string) when calling the .send method:并在调用 .send 方法时传入 null(而不是您的查询字符串):
xmlHttp.send(null);
Also, the "application/x-www-form-urlencoded" header is only used when you're sending serialised parameters but using POST, so remove the xmlHttp.setRequestHeader
line.此外,“application/x-www-form-urlencoded”标头仅在您发送序列化参数但使用 POST 时使用,因此删除xmlHttp.setRequestHeader
行。
More info: https://developer.mozilla.org/en-US/docs/AJAX/Getting_Started更多信息: https : //developer.mozilla.org/en-US/docs/AJAX/Getting_Started
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.