1.在ASP.NET項目中建立一個Web Form,命名為AJAXTest1.aspx,并在其中加入兩個控件,如下:
<form id="form1" runat="server">
<input type="text" id="showDate" runat="server"/>
<input type="button" id="btn" οnclick="btnClick()" value="局部重新整理" runat="server"/>
</form>
2.添加如下JS代碼:
<script type="text/javascript">
function btnClick() {
var xmlHttp = new ActiveXObject("Microsoft.XMLHTTP"); //建立xmlhttp對象
if (!xmlHttp) {
alert("建立xmlhttp異常!");
return;
}
xmlHttp.open("POST", "GetDate.ashx", true); //準備向伺服器的GetDate.ashx發送post請求
//xmlhttp是異步請求,監聽onreadystatechange事件
xmlHttp.onreadystatechange = function () {
if (xmlHttp.readyState == 4) {
if (xmlHttp.status == 200) { //狀态碼為200,表示成功
//alert(xmlHttp.responseText);
document.getElementById("showDate").value = xmlHttp.responseText; //擷取伺服器傳回的文本
}
else {
alert("AJAX伺服器傳回錯誤!");
}
}
}
xmlHttp.send(null); //向伺服器發送請求
}
</script>
3.建立一個Generic Handler檔案,命名為GetDate.ashx,然後添加回傳代碼:
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";
context.Response.Write(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));注:僅添了此行代碼
}
4.用IE浏覽器浏覽AJAXTest1.aspx,效果圖如下:
5.用HttpWatch Professional 檢視伺服器傳回的内容如下圖所示: