考慮以下的網頁,其中透過 XMLHttpRequest 傳送要求至伺服端資源 AjaxDemo.ashx 並取得其回傳結果:
<!DOCTYPE html >
<html>
<head>
<title>示範 XMLHttpRequest </title>
<script>
function runRequest() {
try {
var client = new XMLHttpRequest();
client.open('GET', 'AjaxDemo.ashx', false);
client.send();
document.getElementById('message').innerHTML =client.responseText;
} catch (e) {
document.getElementById('message').innerHTML = e;
}
}
</script>
</head>
<body>
<button onclick="runRequest()">取得伺服器資料</button>
<p id="message"></p>
</body>
</html>
在 ASP.NET Web Forms 裏面想要回應此網頁的要求,必須建立一個泛型處理常式網頁AjaxDemo.ashx 如下:
public class AjaxDemo : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";
context.Response.Write("Hello World");
}
}
網頁執行結果如下:
如果是 ASP.NET MVC ,假設建立一個控制器 AjaxController.cs,於其中建立以下的動作:
public string AjaxDemo()
{
return "Hello World";
}
修改其中的 open 呼叫程式如下:
xhr.open('GET', '/Ajax/AjaxDemo') ;
如此一來可以得到相同的結果。
沒有留言:
張貼留言