一般我们做.net开发,难免会用到ajax,对.net来讲就必须结合着.ashx程序来使用,但一般一个AJAX只对应一个ashx程序,所以当你在一个页面写很多功能的时候,都会对应着很多的方法,这样难免ashx文件就有点多了。。。。
我们如何在一个ashx文件中写多种方法呢,然后让ajax调用同一个ashx文件中的不同方法。好了。不废话了,看代码!
首先是JS代码
$(function () {
//调用getJSON方法
var i = 0;
$.getJSON("DepartmentIndex.ashx?action=See", function (back) {
//解析json
var str1 = "<form><table class='table table-hover table-bordered '>";
var str2 = "<thead><tr><th></th><th>编号</th><th>部门</th><th>人数</th></tr ></thead ><tbody>";
$.each(back, function (k, v) {
str2 += '<tr><td><input type="checkbox"/></td><td>' + v.DepartmentID + "</td><td>" + v.DepartmentName + "</td><td>" + v.People + "</td></tr>"
i++;
});
var str3 = "</tbody></table></form>";
$("#table1").html(str1 + str2 + str3);
$("#count").html("总共有" + i + "条记录");
});
这么一大堆有用的就只有路径,其他的你们应该都懂!!
注意看重点
$.getJSON("DepartmentIndex.ashx?action=See", function (back) {
我的路径后面加了?action=See 这里的See就是参数名,就是找到对应的方法名
接着,我们来看ashx代码!
ashx代码
//判断JS中action的值,对应进入不同的方法
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";
string action = context.Request["action"].ToString();
switch (action)
{
case "DeptSee":
DeptSee(context);
break;
case "See":
See(context);
break;
default:
break;
}
}
//部门数据显示的方法
public void See(HttpContext context)
{
context.Response.ContentType = "text/plain";
List<Department> list = BLL.BLLDepartment.SeeDpatement();
//将list转json
JavaScriptSerializer jss = new JavaScriptSerializer();
string json = jss.Serialize(list);
context.Response.Write(json);
}
/// <summary>
/// 通过部门名称查询部门数据的方法
/// </summary>
/// <param name="context"></param>
public void DeptSee(HttpContext context)
{
context.Response.ContentType = "text/plain";
string name = context.Request["myname"];
List<Department> list = BLL.BLLDepartment.SeeDpatement(name);
//将list转json
JavaScriptSerializer jss = new JavaScriptSerializer();
string json = jss.Serialize(list);
context.Response.Write(json);
}
这里的public void ProcessRequest(HttpContext context)
这个方法就是判断action的值,然后对应进入不同的方法!不同的方法你根据自己要做什么功能,对应写什么方法!
好了,大概就是这样子。写的比较详细了,希望对你们有帮助!
另外需要做程序兼职交流的同学欢迎加群:943149166