springMVC项目中遇到要使用jqueryAjax向前台传递动态表格的需求,原来的做法是在js中接收数据然后拼接成表格再给jsp显示,后来在这个国外的网站上看到了如下的使用“模板”的设计,觉得很是合理,自己测试了一下,觉得比之前js中拼接好用很多,大大减少了js的压力。我就直接复制原作者的回答了(回答真的很详细了),记录一下,感觉自己又成长了。
MyController.java@Controller
public class MyController {
@RequestMapping( method=RequestMethod.GET, value="/mainView" )
public ModelAndView getMainView( ... ) {
/* do all your normal stuff here to build your primary NON-ajax view
* in the same way you always do
*/
}
/* this is the conroller's part of the magic; I'm just using a simple GET but you
* could just as easily do a POST here, obviously
*/
@RequestMapping( method=RequestMethod, value="/subView" )
public ModelAndView getSubView( Model model ) {
model.addAttribute( "user", "Joe Dirt" );
model.addAttribute( "time", new Date() );
return new ModelAndView( "subView" );
}
}
mainView.jsp(...)
function doAjaxPost() {
$.ajax({
type: "GET",
url: "subView",
success: function(response) {
$("#subViewDiv").html( response );
}
});
}
(...)
subView.jsp(...)
User Access Details
${user} accessed the system on ${time}
(...)
下面是原文的地址:
http://stackoverflow.com/questions/4816080/how-to-render-a-view-using-ajax-in-spring-mvc
感谢这位大神!也感谢我伟大的远哥!