JSP之AJAX之一入门篇

[html]  view plain  copy
 print ? 在CODE上查看代码片 派生到我的代码片
  1. <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>  
  2. <%  
  3. String path = request.getContextPath();  
  4. String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";  
  5. %>  
  6.   
  7. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">  
  8. <html>  
  9.   <head>  
  10.     <base href="<%=basePath%>">  
  11.       
  12.     <title>My JSP 'index.jsp' starting page</title>  
  13.     <meta http-equiv="pragma" content="no-cache">  
  14.     <meta http-equiv="cache-control" content="no-cache">  
  15.     <meta http-equiv="expires" content="0">      
  16.     <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">  
  17.     <meta http-equiv="description" content="This is my page">  
  18.     <style type="text/css">  
  19.         #result{border:2px solid #999999;  
  20.             background-color:#eeeeee;  
  21.         }  
  22.     </style>  
  23.     <script type="text/javascript">  
  24.         var xhr;  
  25.         function getTime(){  
  26.         try{  
  27.             //先尝试使用标准方式创建(Firefox、Chrome都支持)  
  28.             xhr=new XMLHttpRequest();  
  29.         }catch(e){  
  30.             //出现异常,意味着IE7之前版本,使用ActiveObject创建。  
  31.             xhr=new ActiveXObject("Microsoft.XMLHttp");  
  32.         }  
  33.         //设置状态变化,回调函数;  
  34.         xhr.onreadystatechange=callback;  
  35.         //设置请求方式和URL  
  36.         xhr.open("get","gettime");  
  37.         //发送请求  
  38.         xhr.send(null);  
  39.         }  
  40.         //状态变化的回调函数;  
  41.         //判断请求完成,并且成功返回  
  42.         function callback(){  
  43.         if(xhr.readyState==4 && xhr.status==200){  
  44.             var resDiv=document.getElementById("result");  
  45.             var old=resDiv.innerHTML;  
  46.             resDiv.innerHTML=old+xhr.responseText+"<br/>";  
  47.         }  
  48.         }  
  49.     </script>  
  50.   </head>  
  51.     
  52.   <body>  
  53.     <input type="button" value='获取服务器时间' onclick='getTime()'/>  
  54.     <div id='result'>  
  55.         这里显示从服务器获取时间,多次点击按钮获取时间,不会刷新整个页面!~  
  56.     </div>  
  57.   </body>  
  58. </html>  

Servlet代码;

[java]  view plain  copy
 print ? 在CODE上查看代码片 派生到我的代码片
  1. resp.setContentType("text/html;charset=utf-8");  
  2.         PrintWriter out=resp.getWriter();  
  3.         Date date=new Date();  
  4.         out.print(date);  
  5.         out.flush();  
  6.         out.close();  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值