看一下您的Ajax请求,我认为您正在尝试发送json对象(但实际上不是),然后您尝试使用@RequestParam而不是@RequestBody获取id的值。
如果您不想在ajax有效负载中发送json对象,则您的内容类型错误。尝试这样的事情。jQuery将data属性转换为查询字符串。
$(document).ready(function(){ $(".overViewListEmployee").click(function () { var id = $(this).find(".overViewEmployeeID").text(); console.log("Works: " + id + "."); $.ajax({ type: "POST", headers: { "Accept" : "text/html", "Content-Type": "application/x-www-form-urlenpred; charset=UTF-8" }, url: "/refreshDetail", //you can get rid of data if you change your url to "/refreshDatil?id="+id data: {"id" : id}, success: function(response) { $(".containerDetailView").html(response); } }); });});如果您确实要发送json对象(如我在评论中已经说过的那样),则需要在控制器级别进行一些更改。
编辑
好的,您现在正在混合两种可能的解决方案。使用当前的ajax对象,您不是在发送json对象,而是普通的http请求。发生ajax请求时,您可以在浏览器中检查“网络”标签,然后会
/refreshDetail?id=yourid在Paylod中看到类似的请求
,而没有json对象。
另一方面,您的控制器
@RequestBody正在尝试从有效负载中获取类似IdObject的对象,但您并未这样做。您的控制器应如下所示:
@RequestMapping(value = "/refreshDetail", method = RequestMethod.POST, produces = MediaType.TEXT_HTML_VALUE)private ModelAndView refreshDetailView(HttpServletRequest hsr, @RequestParam int id, ModelMap model){ model.addAttribute("detailSearchResult", Dao.getDetailViewData(id)); return new ModelAndView("detailView", model);}还要从ajax对象的data属性中删除方括号:
$(".overViewListEmployee").click(function () { var id = parseInt($(this).find(".overViewEmployeeID").text()); console.log("Works: " + id + "."); $.ajax({ type: "POST", accept:"text/html", //contentType: "application/json; charset=utf-8", dataType: "html", url: "/refreshDetail", data: {"id": id}, success: function(response) { $(".containerDetailView").html(response); } });});如果您要发送json负载 如果您真正需要的是从javascript发送json对象,那么您需要更改ajax请求
$(".overViewListEmployee").click(function () { var id = parseInt($(this).find(".overViewEmployeeID").text()); console.log("Works: " + id + "."); $.ajax({ type: "POST", accept:"text/html", dataType: "html", contentType: "application/json", url: "/refreshDetail", data: JSON.stringify({"id": id}), success: function(response) { $(".containerDetailView").html(response); } });});使用contentType
jQuery设置header
Content-Type,告诉您的控制器请求带有json负载。然后,
JSON.stringify将带有要发送的信息的javascript对象转换为json字符串,并将其用作
jQuery有效负载。
在后端,您的控制器现在应该使用,
@RequestBody因为该信息不在请求参数中,而是json负载。因此,它看起来应该像这样:
@RequestMapping(value = "/refreshDetail", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.TEXT_HTML_VALUE) private ModelAndView refreshDetailView(HttpServletRequest hsr, @RequestBody IdObject id, ModelMap model){ model.addAttribute("detailSearchResult", Dao.getDetailViewData(id.getId())); return new ModelAndView("detailView", model); }在这种情况下,请求映射上的consumers属性不是必需的,因为您没有其他任何映射到相同的value
/refreshDetail,但是它使代码更易于阅读。
@ResponseBody在任何一种情况下,您都不必在控制器上使用,因为您要发回视图。发回时会用到它
json,
xml等等。



