簡介:表單方式送出比較耗性能、使用Ajax通路伺服器背景能很大提高性能、以一個簡單的Webform例子為例來進行說明。
1.建立一個空的Webform項目
- 在項目中添加Handlers檔案夾(用于存放一般處理程式響應ajax請求)和Script(用于存放js檔案)檔案夾
2.jQuery——Ajax用法結合Webform實作簡單電腦
一般處理程式的代碼如下
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace WebApplication1.Handlers
{
/// <summary>
/// Handler 的摘要說明
/// </summary>
public class Handler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";
int num1 = Convert.ToInt32(context.Request.Params["num1"]);
int num2 = Convert.ToInt32(context.Request.Params["num2"]);
int result = num1 + num2;
context.Response.Write(result.ToString());
}
public bool IsReusable
{
get
{
return false;
}
}
}
}
- 在項目中添加一個html頁面命名為HtmlPage.html
html頁面的代碼如下
<!DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<style type="text/css">
input {
width: 70px;
}
</style>
<script src="../Scripts/jquery-1.4.1.js" type="text/javascript"></script>
<script type="text/javascript">
$(function () {
$("#btnCal").click(function () {
$.post("Handlers/Handler.ashx", { "num1": $("#txtNum1").val(), "num2": $("#txtNum2").val() },
function (data, status) {
if (status == "success") {
$("#txtResult").val(data);
} else {
alert("資料錯誤!");
}
});
});
});
</script>
</head>
<body>
<input id="txtNum1" type="text" />+<input id="txtNum2" type="text" />
=<input id="txtResult" type="text" />
<input id="btnCal" type="button" value="計算" />
</body>
</html>
2.前端背景互動程式代碼說明
①:建立了一般處理程式Handler.ashx之後、html頁面中的ajax可以通過"Handlers/Handler.ashx"通路該背景服務。
②:html中Ajax送出的資料“num1”、“num2”。在一般處理程式Handler.ashx中可以通過以下方式擷取
int num1 = Convert.ToInt32(context.Request.Params["num1"]);
int num2 = Convert.ToInt32(context.Request.Params["num2"]);
③:$.post()的第三個參數是回調函數、一般處理程式通過context.Response.Write(result.ToString()); 傳回的資料
可以在第三個參數(函數的第一個形參擷取data、第二個參數擷取背景程式執行的情況)
3.Ajax程式說明
1).$(function(){}):是頁面元素架構加載完之後執行的、一般用于綁定元素的點選事件
2).$.post():post請求方式、第一個參數是url、第二個參數json字元串、第三個參數是回調函數
3)$("#btnCal"):是id選擇器、通過id選擇元素
4) $("#txtNum1").val():擷取元素的值
5). $("#txtResult").val(data):給指定的元素指派
如果錯誤之處請指正、謝謝!
本部落格僅做學習記錄之用、如有侵權聯系删除。
可以通過郵箱給我回報[email protected]