首先添加一個html頁其頁面代碼如下:<html>
<head>
<title>在ASP.NET的第一個Ajax小程式</title>
<link rel="stylesheet" type="text/css" href="../css/main.css"/>
<script language="javascript">
var xmlHttp
function showHint(str)
{
if (str.length > 0)
{
var url="GetRequest.aspx?name=" + str
if (window.ActiveXObject) {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlHttp.onreadystatechange=stateChanged
xmlHttp.open("POST", url , true)
xmlHttp.send(null)
}
else
{
document.getElementById("txtHint").innerHTML=""
}
}
function stateChanged()
{
if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete")
{
document.getElementById("txtHint").innerHTML=xmlHttp.responseText
}
}
</script>
</head><body>
<div class=content>
<h1>純Ajax實現的小程式</h1>
<form>
<p>輸入一個字串:<input type="text" id="txt1"onkeyup="showHint(this.value)"></p>
<p>
字串的長度: <span id="txtHint"></span></p>
</form> </div></body>
</html>
述代碼中GetRequest.aspx?name=" + str 指明將請求頁面GetRequest.aspx並把使用者輸入的字串傳遞給頁面GetRequest.aspx,所以下一步就是建立GetRequest.aspx頁面計算字串長度,後台代碼如下:using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
public partial class PureAjax_GetRequest : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (Request.QueryString["name"] != "")
Response.Write(Request.QueryString["name"].Length);
else
Response.Write("NULL");
}
}