在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),希望對大家有所協助,如果大家有任何疑問請給我留言,小編會及時回複大家的。在此也非常感謝大家對雲棲社區網站的支援!