Ajax获取服务器时间案例

版权声明:《==study hard and make progress every day==》 https://blog.csdn.net/qq_38225558/article/details/83719371

页面:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
	<head>
	<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
	<title>通过ajax获取服务器时间</title>
        <script type="text/javascript">
	     	// 创建ajax对象
	    	function createAjax(){
	    		try{
				return new XMLHttpRequest();// 非IE6浏览器,主流浏览器支持的
			}catch(e){
				return new ActiveXObject("Microsoft.XMLHTTP");//IE6浏览器以下创建的核心对象
			}
	    	} 
	    /* 	function createAjax(){
	    		var ajax;//定义局部ajax对象
	    		if(window.XMLHttpRequest){   //判断当前浏览器是否有XMLHttpRequest
	    			ajax = new XMLHttpRequest();// 非IE6浏览器
	    		} else {
	    			ajax = new ActiveXObject("Microsoft.XMLHTTP");	// IE6浏览器
	    		}
	    		return ajax;
	    	}  */
        	// 获取服务器时间的方法
        	function clickTime(){
        		// 1.创建ajax
        		var ajax = createAjax();
        		// 2.以异步方式发出get请求  true:异步     false:同步
				ajax.open("get","/zq/getTime?"+ new Date().toGMTString(),true); //注意:发送请求的时候要加时间戳,因为有些浏览器是自带缓存功能,如果自带缓存功能,它就不会发送请求去后端,它直接在缓存中获取到数据了
        		// 3.监听ajax状态,http响应状态       (注意:必须放在send之前执行)
        		ajax.onreadystatechange = function(){
          			if(ajax.readyState == 4 && ajax.status == 200){  //ajax已经处理完成并且http响应状态是200
          				//获取后台返回的数据
					/* alert(ajax.responseText ); */
					document.getElementById("time").innerHTML=ajax.responseText;
        			}
        		}
        		// 4.发出请求
        		ajax.send();
        	}
        </script>
	</head>
	<body>
		<input type="button" onclick="clickTime();" value="获取时间"/>
		<span id="time" style="color: red"></span>
	</body>
</html>

service:

/**
 * 获取服务端时间:
 * 注意:异步技术必须加@ResponseBody
 * @author 郑清
 */
@Controller
public class TimeController {
	
	@RequestMapping("/getTime")
	@ResponseBody
	public String getTimer(HttpServletResponse resp) throws UnsupportedEncodingException{
		resp.setContentType("text/html;charset=utf-8");//解决乱码问题
		System.out.println(new Date().toLocaleString());
		return new Date().toLocaleString();
	}
	
}

运行效果:

猜你喜欢

转载自blog.csdn.net/qq_38225558/article/details/83719371