近來我發現我一些同事。在用ajax時,用資料來源,都喜歡重新建立一個頁面.其實我是很不喜歡這種模式,主要原因,一是後期維護麻煩,還要去找哪些頁面,二是不能調用一些本頁原有的資料方法.因此我在這裡做了一個測試的案例。如下
CS代碼
1 using System; 2 using System.Data; 3 using System.Configuration; 4 using System.Collections; 5 using System.Web; 6 using System.Web.Security; 7 using System.Web.UI; 8 using System.Web.UI.WebControls; 9 using System.Web.UI.WebControls.WebParts;10 using System.Web.UI.HtmlControls;11 using System.Web.Services;12 13 public partial class TestAjax : System.Web.UI.Page14 {15 protected void Page_Load(object sender, EventArgs e)16 {17 string methor = Request["act"];18 if (!string.IsNullOrEmpty(methor))19 {20 this.GetType().GetMethod(methor).Invoke(this, null);21 }22 23 }24 25 public void GetVal()26 {27 string val = "getVal 方法擷取參數" + Request["arg"];28 Response.Clear();29 Response.Write(val);30 Response.End();31 }32 33 }
aspx頁面
1 <%@ Page Language="C#" AutoEventWireup="true" CodeFile="TestAjax.aspx.cs" Inherits="TestAjax" %> 2 3 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 4 5 <html xmlns="http://www.w3.org/1999/xhtml" > 6 <head runat="server"> 7 <title>無標題頁</title> 8 <script type="text/javascript" src="Js/jquery-1.8.1.min.js" language="javascript"></script> 9 <script language="javascript" type="text/javascript">10 11 function test()12 {13 14 var data = new Object();15 data.act = "GetVal";16 data.arg = "123";17 $.post("TestAjax.aspx", data, function (data) { alert(data); });18 }19 </script>20 21 22 </head>23 <body>24 <form id="form1" runat="server">25 <div>26 <input id="Button1" onclick="test()" type="button" value="測試ajax" />27 28 </div>29 </form>30 </body>31 </html>