示例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>