示例1:取得服务端时间javascript
1. 开发服务端,创建通常处理程序css
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace AJAX1 { /// <summary> /// AJAXGetTime 的摘要说明 /// </summary> public class AJAXGetTime : IHttpHandler { public void ProcessRequest(HttpContext context) { context.Response.ContentType = "text/plain"; //如下的这些都是清除缓存用的,由于用get的方法时,若是有缓存,则回应是从缓存中读取的。 context.Response.Buffer = true; context.Response.Expires = 0; context.Response.ExpiresAbsolute = DateTime.Now.AddDays(-1); context.Response.AddHeader("pragma", "no-cache"); context.Response.AddHeader("cache-control", "private"); context.Response.CacheControl = "no-cache"; string id = context.Request["id"]; context.Response.Write(DateTime.Now.ToString()+"-->"+id); } public bool IsReusable { get { return false; } } } }
2.开发客户端,创建普通 的html页面,用JavaScript建立XMLHTTPRequest,此示例是IE的xmlhttp的,若是用到其它内核的浏览器则要建立其它浏览器的xmlhttprequest.html
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title></title> <meta HTTP-EQUIV="pragma" CONTENT="no-cache" /> <meta HTTP-EQUIV="Cache-Control" CONTENT="no-cache, must-revalidate" /> <meta HTTP-EQUIV="expires" CONTENT="0" /> <script type="text/javascript"> function gettime() { var xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");//建立xmlhttp对象,至关于建立webclient if (!xmlhttp) { alert("建立xmlhttp对象异常."); return; } xmlhttp.open("GET", "AJAXGetTime.ashx?id="+encodeURI("国家名称"), false); //准备向服务器AJAXGetTime.ashx发出post请求 //XMLHTTP默认(也推荐)不是同步请求的,也就是open方法并不像webclient的downloadString那样把服务器返回的数据拿到才返回,是异步的。所以须要监听onreadystatechange事件 xmlhttp.onreadystatechange = function () { if (xmlhttp.readyState == 4) {//4表示数据已返回了 if (xmlhttp.status == 200) { //返回成功 document.getElementById("Text1").value = xmlhttp.responseText; //responseText属性为服务器返回的文本. } else { alert("AJAX服务器返回错误."); //此时才开始发送请求 return; } } } xmlhttp.send(); } </script> <style type="text/css"> #Text1 { width: 449px; } </style> </head> <body> <p> <input id="Text1" type="text" /><input id="Button1" type="button" value="GetServerTime" onclick="gettime();" /></p> </body> </html>