JSP之AJAX之一入门篇

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'index.jsp' starting page</title>
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">    
	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
	<meta http-equiv="description" content="This is my page">
	<style type="text/css">
		#result{border:2px solid #999999;
			background-color:#eeeeee;
		}
	</style>
	<script type="text/javascript">
		var xhr;
		function getTime(){
		try{
			//先尝试使用标准方式创建(Firefox、Chrome都支持)
			xhr=new XMLHttpRequest();
		}catch(e){
			//出现异常,意味着IE7之前版本,使用ActiveObject创建。
			xhr=new ActiveXObject("Microsoft.XMLHttp");
		}
		//设置状态变化,回调函数;
		xhr.onreadystatechange=callback;
		//设置请求方式和URL
		xhr.open("get","gettime");
		//发送请求
		xhr.send(null);
		}
		//状态变化的回调函数;
		//判断请求完成,并且成功返回
		function callback(){
		if(xhr.readyState==4 && xhr.status==200){
			var resDiv=document.getElementById("result");
			var old=resDiv.innerHTML;
			resDiv.innerHTML=old+xhr.responseText+"<br/>";
		}
		}
	</script>
  </head>
  
  <body>
    <input type="button" value='获取服务器时间' οnclick='getTime()'/>
    <div id='result'>
    	这里显示从服务器获取时间,多次点击按钮获取时间,不会刷新整个页面!~
    </div>
  </body>
</html>

Servlet代码;

resp.setContentType("text/html;charset=utf-8");
		PrintWriter out=resp.getWriter();
		Date date=new Date();
		out.print(date);
		out.flush();
		out.close();


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

teayear

读后有收获可以获取更多资源

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值