jQuery ajax调用后台aspx后台文件的两种常见方法(不是ashx)
在asp.netwebForm开发中,用Jqueryajax调用aspx页面的方法常用的有两种:下面我来简单介绍一下。
(1)通过aspx.cs的静态方法+WebMethod进行处理
简单的介绍下WebMethod方法的用法
1.修饰符主要用publicstatic修饰
2.方法前面加上[WebMethod]属性表明这是WebMethod方法
3.前台html页面(Client端)访问时要使用post方法,和后台.cs文件进行数据交互,否则会返回整个html页面。
4.当后台页面返回数据后,前台html页面需要用data.d接收返回的json字符串。
5.访问url:http://abc.com/abc.aspx/ajax方法
aspx.cs代码:
usingSystem.Web.Services;
[WebMethod]
publicstaticstringSayHello()
{
return"HelloAjax!";
}
前台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代码:
<formid="form1"runat="server"> <div> <asp:ButtonID="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代码:
<%@WebHandlerLanguage="C#"Class="AjaxHandler"%>
usingSystem;
usingSystem.Web;
publicclassAjaxHandler:IHttpHandler{
publicvoidProcessRequest(HttpContextcontext){
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");
}
}
publicboolIsReusable{
get{
returnfalse;
}
}
}
以上所述是小编给大家介绍的jQueryajax调用后台aspx后台文件的两种常见方法(不是ashx),希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对毛票票网站的支持!