一句話概括:Ajax 就是用 JavaScript 腳本存取資料的技術,讓網頁能在不重載整頁的情況下完成局部更新。
目前各家瀏覽器都支援 XMLHttpRequest 物件(IE5、IE6 需透過 ActiveXObject)。向後端請求資料時,readyState 有五個狀態:
每改變一次狀態就會觸發一次 onreadystatechange 事件;而 status 常見的值如 200(OK)與 404(未找到頁面)。
<html xmlns="https://www.w3.org/1999/xhtml">
<head runat="server">
<title>無標題頁</title>
<script type="text/javascript">
function getName() {
var xmlhttp;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
alert("你好:" + xmlhttp.responseText);
}
};
xmlhttp.open("post", "Default.aspx?id=gname", true);
xmlhttp.send();
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<input id="Button1" type="button" value="button" onclick="getName()" />
</div>
</form>
</body>
</html>
protected void Page_Load(object sender, EventArgs e)
{
if (Request["id"] != null)
{
Response.Write("張三");
Response.End(); // 立刻結束回應,避免整份頁面被輸出
}
}
這裡的 Response.End() 是關鍵:一般處理常式或 Web 表單若不加這行,整頁的 HTML 都會被當成回應內容送出。若改成 .ashx 一般處理常式,就不需要這個技巧,語意也更清楚。