Neu*_*ino 26 ajax jquery spring-mvc
我正在使用Spring MVC,我需要对服务器进行异步调用,并且只刷新页面的一部分.
我实际拥有的是一个返回String的Controller.我使用JQuery(.post())函数调用Controller .
我的解决方案的问题是,当我使用ModelAndView作为返回类型时,我无法像我那样呈现JSP.
有没有办法返回已经呈现的视图?
提前致谢.
Neuquino
Ban*_*ane 59
这个答案只是确认axtavt的答案是有效的.我花了一分钟才意识到他的建议是什么,所以我想我会发布一个代码片段来帮助任何跟在我后面的人.不过,感激不尽的是他!:)
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.GET, value="/subView" )
public ModelAndView getSubView( Model model ) {
model.addAttribute( "user", "Joe Dirt" );
model.addAttribute( "time", new Date() );
return new ModelAndView( "subView" );
}
}
Run Code Online (Sandbox Code Playgroud)
mainView.jsp
(...)
<script src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
<script type="text/javascript">
function doAjaxPost() {
$.ajax({
type: "GET",
url: "subView",
success: function(response) {
$("#subViewDiv").html( response );
}
});
}
</script>
<input type="button" value="GO!" onclick="doAjaxPost();" />
<div id="subViewDiv"></div>
(...)
Run Code Online (Sandbox Code Playgroud)
subView.jsp
(...)
<h3>
User Access Details
</h3>
<p>
${user} accessed the system on ${time}
</p>
(...)
Run Code Online (Sandbox Code Playgroud)
就是这样!一件美丽的事; 到目前为止,在Spring中做AJAX一直是一个巨大的痛苦......解析大@Responbody,通过连接JS中的东西来构建大量的HTML ......呃......我简直不敢相信这种方法是多么的简单和令人敬畏 - 直到现在才意识到这一点!:)
| 归档时间: |
|
| 查看次数: |
32946 次 |
| 最近记录: |