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; } } }?
? (3)注意:當要返回一個泛型數組,枚舉等不是字符串的時候需要對返回的內容進行JSON序列化,序列化代碼如下:
??????
JavaScriptSerializer jsonUtil = new JavaScriptSerializer();string json = jsonUtil.Serialize(需要返回的對象);?? (4)序列完后前臺html頁面接收需要用each遍歷時,因為in對字符串不管用,所以要對傳過來的字符串進行Json化,代碼如下
$.get(url,function(data){ obj= $.parseJSON(data); //Json化之后可以用each遍歷$.each(obj, function(k,v) { alert(v.id); }); });?
轉載于:https://www.cnblogs.com/GreenLeaves/p/5624044.html
總結
以上是生活随笔為你收集整理的Jquery ajax调用后台aspx后台文件方法(不是ashx)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Linux下Rsync+Inotify-
- 下一篇: Angular面试从喜剧到悲剧的十个问题