ajax如何调用本页数据源不用一般处理程序
近来我发现我一些同事。在用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.Page 14 { 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>