1. 程式人生 > >前臺訪問後臺的幾種方法

前臺訪問後臺的幾種方法

1、WebMethod

public static方法,ajax/PageMethods呼叫。

後臺方法,test.cs

[WebMethod]
 public static string GetUserName() 
 {
 //......
 }
需要訪問操作session時
[WebMethod(EnableSession = true)]//或[WebMethod(true)]
 public static string GetUserName() 
 {
 //......
 }

前臺js直接呼叫,test.aspx

PageMethods.GetUserName

前臺ajax呼叫,test.js

$.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的簡單封裝,jquery.extend.js

///	<summary>
///     jQuery原型擴充套件,重新封裝Ajax請求WebServeice
///	</summary>
///	<param name="url" type="String">
///     處理請求的地址
///	</param>
///	<param name="dataMap" type="String">
///     引數,json格式的字串
///	</param>
///	<param name="fnSuccess" type="function">
///     請求成功後的回撥函式
///	</param>
$.ajaxWebService = function(url, dataMap, fnSuccess) {
    $.ajax({
        type: "POST",
        contentType: "application/json",
        url: url,
        data: dataMap,
        dataType: "json",
        success: fnSuccess
    });
}

請求方法

$.ajaxWebService("WebForm2.aspx/GetUserName", "{}", function(result) {......});

2、一般處理程式(*.ashx)

處理速度比aspx快,是專為ajax服務。
接受引數用context.Request[" "];
編寫多個方法使用Switch語句;
返回值用context.Response.Write( );

前臺呼叫

DefaultHandler.ashx?method=getlist

後臺CS

  using System;
  using System.Web;
  using System.Collections.Generic; 
  using System.Web.Script.Serialization;
   
  public class DefaultHandler  IHttpHandler { 
  public void ProcessRequest (HttpContext context) 
  {
  string response = string.Empty;
  string str = context.Request.QueryString["method"]; 
   
  if (string.IsNullOrEmpty(str)) 
  { 
  context.Response.Write("error!"); 
  return; 
  } 
   
  switch (str) 
  { 
  case "getlist" 
  response = GetList(context); 
  break; 
  //下邊還有可以接著寫. 
  } 
  context.Response.Write(response);
  context.Response.End();
   
  } 
   
  public bool IsReusable { 
  get { 
  return false; 
  } 
  } 
   
  public string GetList(HttpContext context) 
  {
   
  //從資料庫取得list資料: 
  List<myEntity> data = DAL.GetData();
   
  return ToJson(data.ToArray());
   
  } 
   
  //序列化物件為json資料 
  public string ToJson(object o) 
  { 
  JavaScriptSerializer j = new JavaScriptSerializer(); 
  return j.Serialize(o); 
  }
  
  } 
   


3、web服務(*.asmx)

必須是json格式、跨瀏覽器、跨平臺。

 4、直接嵌入 前臺html或者js裡直接嵌入後臺的public方法/屬性 <%=abc()%>
 $(document).ready(function() {  
 sshow();  
 });  
   
 function sshow()  
 {    
      var s = '<%=IsShow() %>';    
      if(s == '0')  
      {  
       document.getElementById("trr").style.display= "none";       
      }else  
      {  
      document.getElementById("trr").style.display= "";   
      }  
      alert(s);  
 }  

public int IsShow()  
   {  
       int sis = 0;  
       ASPxLabel urll = (ASPxLabel)DataList1.Items[0].FindControl("ASPxLabelURL");  
       //Response.Write(urll.Text.Length);  
       //Response.Write(urll.Text.IndexOf(".", 9, 2).ToString());  
       if (urll.Text.Length > 12)  
       {  
           if (urll.Text.IndexOf(".", 9, 3) > -1)  
           {  
               sis = 1;  
           }  
       }  
       return sis;  
   }