首先在 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(){.......}
});
復制代碼 代碼如下:
<%@ 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="jquery.js"></script>
</head>
<body>
<input type="button" value="調用Test"/><input type="button" value="調用Test1"
onclick="CallMethod('Test1')"/><input type="button" value="調用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>
新聞熱點
疑難解答
圖片精選