jQuery ajax調用後台aspx後台檔案的兩種常見方法(不是ashx)_jquery

來源:互聯網
上載者:User

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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.