更新jsp页面的内容而不刷新

问题描述:

我有一个显示表格内容的jsp页面。 用户查看页面时,表格的内容会逐秒更改。 因此,用户必须每次刷新页面以查看新鲜和更新的内容。 如何更新jsp页面的内容而不必刷新页面。 我想要一个功能,就像gmail.com一样,邮箱的大小不断增加,用户不会刷新。更新jsp页面的内容而不刷新

你应该看看使用Ajax(jQuery是我的首选方法)。

http://api.jquery.com/jQuery.get/

http://api.jquery.com/jQuery.post/

这将然后打一个控制器,它会回报你想要的数据而无需刷新页面。

因此,举例来说,如果你有一个login.jsp的...

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> 
<%@ page session="true" %> 
<html> 
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script> 
<head> 
    <title>Login</title> 
</head> 
<body> 
<h1> 
    Hello please login to this application 
</h1> 
<script> 

     function login(){ 
      var username = $("#username").val(); 
      var password = $("#password").val(); 

      $.post('login', { username : username , password : password }, function(data) { 
       $('#results').html(data).hide().slideDown('slow'); 
      }); 
     } 

</script> 
Username : <input id="username" type="text" /> 
Password : <input id="password" type="password" /> 
<input name="send" type="submit" value="Click me" onclick="login()" /> 
<form name="next" action="auth/details" method="get"> 
    <input name="send" type="submit" value="Go Through"/> 
</form> 
<div id="results" /> 
</body> 
</html> 

在你的控制,你会然后打的型号,但为了简单起见,我做了一个很简单的例子.. 。

/** 
* Handles requests for the application home page. 
*/ 
@Controller 
public class LoginController { 

    private static final Logger logger = LoggerFactory.getLogger(LoginController.class); 

    Util util; 

    /** 
    * Simply selects the home view to render by returning its name. 
    */ 
    @RequestMapping(value = "/login", method = RequestMethod.POST) 
    public String home(Locale locale, Model model, String username, String password) { 


     if(username.equalsIgnoreCase("david")) 
     { 
      model.addAttribute("validUser", "Welcome " + username); 

      return "home"; 
     } 
     else 
     { 
      model.addAttribute("validUser", "Incorrect username and password"); 
      return "home"; 
     } 

    } 

} 

这再加入HTML缓慢滚动位到div说,如果它是有效的,为家庭的代码如下...

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> 
<%@ page session="true" %> 
<html> 
<body> 
<P> ${validUser}. </P> 
</body> 
</html> 
+0

你能提供做同样的JSP页面的样本数据。 – 2012-02-14 16:23:35

+0

示例添加的重要位是$ .post ... – david99world 2012-02-14 16:38:08

可以使Ajax请求,并从服务器提取数据,并使用Java脚本来渲染视图上

+1

您可以提供一个jsp页面的样本做同样的 – 2012-02-14 16:24:34