用juery的ajax方法調用aspx.cs頁面中的webmethod方法

首先在 aspx.cs文件裏建一個公開的靜態方法,然後加上WebMethod屬性。
如:

[WebMethod]
public static string GetUserName()
{
    //...
}
 

<pre class="csharp" name="code">  如果要在這個方法裏操作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

<%@ 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" οnclick="CallMethod('Test')"/><input type="button" value="調用Test1" 

  

οnclick="CallMethod('Test1')"/><input type="button" value="調用Test2" οnclick="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('出錯了');}     

        }

      );

}) 
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章