jQuery ajax Two common ways to call background aspx background files of is not ashx

  • 2021-07-01 06:21:19
  • OfStack

In the development of asp. net webForm, there are two common methods to call aspx pages with Jquery ajax: I will briefly introduce 1 below.

(1) Processing by static method of aspx. cs + WebMethod

Briefly introduce the usage of WebMethod method

1. Modifiers are mainly modified with public static

2. The method is preceded by the [WebMethod] attribute to indicate that it is an WebMethod method

3. When the foreground html page (Client side) is accessed, the post method should be used to interact with the background. cs file, otherwise the whole html page will be returned.

4. When the background page returns data, the foreground html page needs to receive the returned json string with data. d.

5. Access url: http://abc.com/abc. aspx/ajax method

aspx. cs code:


using System.Web.Services; 
[WebMethod]
public static string SayHello()
{
return "Hello Ajax!";
}

Foreground jquery code:


$(function() { 
$("#btn").click(function() { 
$.ajax({ 
type: "post", // To use post Mode  
url: "Demo.aspx/SayHello",// Method page and method name 
contentType: "application/json; charset=utf-8", 
dataType: "json", 
success: function(data) { 
alert(data.d);// The returned data is used with the data.d Get content 
},
error: function(err) { 
alert(err); 
} 
});
}); 
});

html code:


<form id="form1" runat="server">
<div>
<asp:Button ID="btn" runat="server" Text=" Authenticate the user " />
</div>
</form>

(2) Processing by a general processing program ashx;

Jquery code:


$.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 code:


<%@ 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; 
} 
} 
}

Related articles: