1. GetTime.html
1 <!DOCTYPE html> 2 <html xmlns="http://www.w3.org/1999/xhtml"> 3 <head> 4 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 5 <title></title> 6 <script type="text/javascript"> 7 window.onload = function () { 8 document.getElementById("btnGetTime").onclick = function () { 9 //向服务器请求时间 10 //1. 创建异步对象(小浏览器) 11 var xhr = new XMLHttpRequest(); 12 //2. 设置参数(请求方式,请求页面,是否异步) 13 xhr.open("get", "GetTime.ashx?name=huoaa", true); 14 //3. 让get请求不从浏览器获取缓存数据 15 xhr.setRequestHeader("If-Modified-Since", "0"); 16 //4. 设置回掉函数 17 xhr.onreadystatechange = function () { 18 if (xhr.readyState == 4 && xhr.status == 200) { 19 var res = xhr.responseText; 20 alert(res); 21 } 22 }; 23 //4. 发送异步请求 24 xhr.send(null); 25 }; 26 document.getElementById("btnPostTime").onclick = function () { 27 //向服务器请求时间 28 //1. 创建异步对象(小浏览器) 29 var xhr = new XMLHttpRequest(); 30 //2. 设置参数(请求方式,请求页面,是否异步) 31 xhr.open("post", "GetTime.ashx", true); 32 //3. 针对post请求不会产生浏览器端缓存 33 //xhr.setRequestHeader("If-Modified-Since", "0"); 34 //设置表单传送数据的默认编码方式 35 xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); 36 //4. 设置回掉函数 37 xhr.onreadystatechange = function () { 38 if (xhr.readyState == 4 && xhr.status == 200) { 39 var res = xhr.responseText; 40 alert(res); 41 } 42 }; 43 //4. 发送异步请求 44 //post传参方式 45 xhr.send("name=huoaa"); 46 }; 47 }; 48 </script> 49 </head> 50 <body> 51 <input type="button" value="get获取服务器时间" id="btnGetTime" /> 52 <input type="button" value="post获取服务器时间" id="btnPostTime" /> 53 </body> 54 </html>
2. GetTime.ashx
1 <%@ WebHandler Language="C#" Class="Get请求" %> 2 3 using System; 4 using System.Web; 5 6 public class Get请求 : IHttpHandler { 7 8 public void ProcessRequest (HttpContext context) { 9 context.Response.ContentType = "text/plain"; 10 string name = context.Request.Params["name"]; 11 context.Response.Write(DateTime.Now.ToString()+",name="+name); 12 } 13 14 public bool IsReusable { 15 get { 16 return false; 17 } 18 } 19 20 }