jQuery ajax调用后台aspx后台文件的两种常见方法(不是ashx)

在asp.net webForm开发中,用Jquery ajax调用aspx页面的方法常用的有两种:下面我来简单介绍一下。

(1)通过aspx.cs的静态方法+WebMethod进行处理

简单的介绍下WebMethod方法的用法

1.修饰符主要用public static修饰

2.方法前面加上[WebMethod]属性表明这是WebMethod方法

3.前台html页面(Client端)访问时要使用post方法,和后台.cs文件进行数据交互,否则会返回整个html页面。

4.当后台页面返回数据后,前台html页面需要用data.d接收返回的json字符串。

5.访问url:http://abc.com/abc.aspx/ajax方法

aspx.cs代码:

using System.Web.Services; 
[WebMethod]
public static string SayHello()
{
return "Hello Ajax!";
}

前台jquery代码:

$(function() { 
$("#btn").click(function() { 
$.ajax({ 
type: "post", //要用post方式 
url: "Demo.aspx/SayHello",//方法所在页面和方法名
contentType: "application/json; charset=utf-8", 
dataType: "json", 
success: function(data) { 
alert(data.d);//返回的数据用data.d获取内容
},
error: function(err) { 
alert(err); 
} 
});
}); 
});

html代码:

<form id="form1" runat="server">
<div>
<asp:Button ID="btn" runat="server" Text="验证用户" />
</div>
</form>

(2)通过一般处理程序ashx进行处理;

Jquery代码:

$.ajax({ 
type: "POST", 
url: "S_CBFBM.ashx", 
data: { ZBM: p_zdm }, 
beforeSend: function() { 
//$("#div_load").visible = "true; 
}, 
success: function(msg) { 
//$("#div_load").visible = false; 
$("#ds").html("<p>" + msg + "</p>"); 
$("#CBFBM").val(msg); 
} 
});

ashx.cs代码:

<%@ WebHandler Language="C#" Class="AjaxHandler" %> 
using System; 
using System.Web; 
public class AjaxHandler : IHttpHandler { 
public void ProcessRequest (HttpContext context) { 
context.Response.ContentType = "text/plain"; 
if (context.Request["name"].ToString() == "admin" && 
context.Request["pass"].ToString() == "admin") 
{ 
context.Response.Write("Y"); 
} 
else 
{ 
context.Response.Write("N"); 
} 
} 
public bool IsReusable { 
get { 
return false; 
} 
} 
}

以上所述是小编给大家介绍的jQuery ajax调用后台aspx后台文件的两种常见方法(不是ashx),希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对来客网网站的支持!