用juery的ajax方法调用aspx.cs页面中的webmethod方法示例
            网络编程 发布日期:2025/11/4 浏览次数:1
         
        
            正在浏览:用juery的ajax方法调用aspx.cs页面中的webmethod方法示例
            首先在 aspx.cs文件里建一个公开的静态方法,然后加上WebMethod属性。 
如: 
[WebMethod] 
public static string GetUserName() 
{ 
//...... 
} 
  如果要在这个方法里操作session,那还得将WebMethod的EnableSession 属性设为true 。即: 
[WebMethod(EnableSession = true)]//或[WebMethod(true)] 
public static string GetUserName() 
{ 
//...... 
} 
 然后我们就写ajax程序来访问这个程序,我们就用jQuery吧。 
复制代码 代码如下: 
$.ajax({ 
type: "POST", 
contentType: "application/json", 
url: "WebForm2.aspx/GetUserName", 
data: "{}", 
dataType: "json", 
success: function(){.......} 
}); 
 
type:请求的类型,这里必须用post 。WebMethod方法只接受post类型的请求。 
contentType:发送信息至服务器时内容编码类型。我们这里一定要用 application/json 。 
url:请求的服务器端处理程序的路径,格式为"文件名(含后缀)/方法名" 
data:参 数列表。注意,这里的参数一定要是json格式的字符串,记住是字符串格式,如:"{aa:11,bb:22,cc:33 , ...}"。如果你写的不是字符串,那jquery会把它实序列化成字符串,那么在服务器端接受到的就不是json格式了,且不能为空,即使没有参数也要 写成"{}",如上例。 
很多人不成功,原因就在这里。 
dataType:服务器返回的数据类型。必须是json,其他的都无效。因为 webservice 是一json格式返回数据的,其形式为:{"d":"......."}。 
success:请求成功后的回调函数。你 可以在这里对返回的数据做任意处理。 
下面给个ajax请求自身页面的例子给你测试。。。 
test.aspx 
XML/HTML code 
复制代码 代码如下: 
<%@ Page language="C#"%> 
<script runat="server"> 
protected void Page_Load(object sender,EventArgs e){ 
Response.Charset="gb2312"; 
if(Request.Form["method"]=="Test")Test(); 
else if(Request.Form["method"]=="Test1")Test1(); 
else if(Request.Form["method"]=="Test2")Test2(); 
Response.Write("一般请求<br/>"); 
} 
public void Test() 
{ 
Response.Write("执行Test方法"+DateTime.Now); 
Response.End();//停止其他输出 
} 
public void Test1() 
{ 
Response.Write("执行Test1方法"+DateTime.Now); 
Response.End();//停止其他输出 
} 
public void Test2() 
{ 
Response.Write("执行Test2方法"+DateTime.Now); 
Response.End();//停止其他输出 
} 
</script> 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
<html xmlns="http://www.w3.org/1999/xhtml"> 
<head runat="server"> 
<meta http-equiv="content-type" content="text/html;charset=gb2312" /> 
<script type="text/javascript" src="/UploadFiles/2021-04-02/jquery.js"></head> 
<body> 
<input type="button" value="调用Test" onclick="CallMethod('Test')"/><input type="button" value="调用Test1" 
onclick="CallMethod('Test1')"/><input type="button" value="调用Test2" onclick="CallMethod('Test2')"/> 
<script type="text/javascript"> 
function CallMethod(method){ 
$.ajax( 
{ 
type: "POST", 
url: "test.aspx", 
data:{method:method}, 
success:function(msg){alert(msg);}, 
error: function(){alert('出错了');} 
} 
) 
} 
$(document).ready(function(){ 
$.ajax( 
{ 
type: "POST", 
url: "test.aspx", 
data:{method:"Test"}, 
success:function(msg){alert("$(document).ready执行方法Test返回结果\n\n\n"+msg);}, 
error: function(){alert('出错了');} 
} 
); 
}) 
</script> 
</body> 
</html>