springMVC项目中遇到要使用jqueryAjax向前台传递动态表格的需求,原来的做法是在js中接收数据然后拼接成表格再给jsp显示,后来在这个国外的网站上看到了如下的使用“模板”的设计,觉得很是合理,自己测试了一下,觉得比之前js中拼接好用很多,大大减少了js的压力。我就直接复制原作者的回答了(回答真的很详细了),记录一下,感觉自己又成长了。

MyController.java

@ControllerpublicclassMyController{@RequestMapping(method=RequestMethod.GET,value="/mainView")publicModelAndViewgetMainView(...){/*doallyournormalstuffheretobuildyourprimaryNON-ajaxview*inthesamewayyoualwaysdo*/}/*thisistheconroller'spartofthemagic;I'mjustusingasimpleGETbutyou*couldjustaseasilydoaPOSThere,obviously*/@RequestMapping(method=RequestMethod,value="/subView")publicModelAndViewgetSubView(Modelmodel){model.addAttribute("user","JoeDirt");model.addAttribute("time",newDate());returnnewModelAndView("subView");}}

mainView.jsp

(...)<scriptsrc="http://code.jquery.com/jquery-1.7.1.min.js"></script><scripttype="text/javascript">functiondoAjaxPost(){$.ajax({type:"GET",url:"subView",success:function(response){$("#subViewDiv").html(response);}});}</script><inputtype="button"value="GO!"onclick="doAjaxPost();"/><divid="subViewDiv"></div>(...)

subView.jsp

(...)<h4>UserAccessDetails</h4><p>${user}accessedthesystemon${time}</p>(...)


下面是原文的地址:

http://stackoverflow.com/questions/4816080/how-to-render-a-view-using-ajax-in-spring-mvc


感谢这位大神!也感谢我伟大的远哥!