在asp.net webForm开发中,用jquery ajax调用aspx页面的方法常用的有两种:下面我来简单介绍一下,现在小编就来说说关于jquery中ajax方法的使用?下面内容希望能帮助到你,我们来一起看看吧!

jquery中ajax方法的使用(ajax调用后台aspx后台文件方法)

jquery中ajax方法的使用

在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; } } }

,