本例演示在 ASP.NET 中配合 jQuery 實現異步刷新:輸入框失去焦點時,異步請求後台處理程序並把結果寫回另一個輸入框。
<script src="Scripts/jquery-1.4.1.min.js"></script>
<script type="text/javascript">
// 方案二(推薦):在 ready 中綁定 blur 事件
$(document).ready(function () {
$("#text1").blur(function () {
$.post("test1.ashx", { "Name": $("#text1").val() }, function jy(data) {
$("#text2").val(data);
});
});
});
</script>
<input type="text" id="text1" /> 轉換
<input type="text" id="text2" />
(方案一也可直接在 text1 上寫 onblur="sys()" 觸發 $.post,效果相同。)
using System.Web;
namespace 異步刷新 {
public class test1 : IHttpHandler {
public void ProcessRequest(HttpContext context) {
context.Response.ContentType = "text/plain";
string name = context.Request["Name"];
context.Response.Write(name);
}
public bool IsReusable {
get { return false; }
}
}
}
ProcessRequest 中讀取傳入的 Name 並寫回響應,前端回調再把結果填入 #text2,實現無刷新異步處理。