HTML/JSP页面动态显示时间(通过jquery或ajax实现)

设置定时器

setInterval(函数,毫秒数)
每隔n毫秒就会调用一次函数
方式一. 动态显示时间

<script>
    setInterval(function () {
    
    
        $("#d1").html(new Date().toLocaleString());
    },1000);
</script>

方式二. Springmvc中利用与控制器异步交互获取当前格式化的时间
前台代码

<style>
  #d1{
    
    
            color: #FF5722;
            font:bold 20px 'Arial Black';
        }
</style>
<script>
    setInterval(function () {
    
    
        $.get("${context}/date/get",{
    
    },function (data) {
    
    
            $("#d1").html(data.dateStr);
        })
    },1000);
</script>

控制器代码

@Controller
@RequestMapping("date")
@ResponseBody
public class  DateController {
    
    
    @RequestMapping("/get")
    public Map<String, String> get(){
    
    
        Map<String,String> map = new HashMap<>();
        Date date=new Date();
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String dateStr = sdf.format(date);
        map.put("dateStr",dateStr);
        return map;
    }
}

方式三. jsp中通过<% %>,这种方式会获取一次时间,时间获取了一次就固定不变了,除非刷新页面

<script>
       setInterval(function () {
    
    
       <%  
       Date date=new Date();
      %>
        $("#d1").html("<% date %>");
    },1000);

猜你喜欢

转载自blog.csdn.net/a347635191/article/details/94608914