項目開發過程中很多地方都需要前端和背景資料互動,幾種典型常用的方法如利用控制項的AutopostBack屬性、Button提交表單等等。但這些都是有條件的,AutoPostBack具有即時性但會重新整理頁面,Button提交表單不能實現資料互動的即時性。當然說到前台與背景資料互動更不能漏掉ajax,ajax實現前台與後台資料的非同步互動,並且保證即時的、局部重新整理。但有些資料不需要非同步互動,例如當互動的資料是下一步執行的條件時,就必須要等到資料前台與後台資料互動完成後才能繼續執行程式。所以對於掌握js與後台資料互動的方法還是很有必要的。
方法一
後台方法:
// 需要標識為WebMethod [System.Web.Services.WebMethod]// 注意,要讓前台調用的方法,一定要是public和static的 public static string Say(string name){string result = "Hello:" + name;return result;}
前台js:
<script type="text/javascript">function btnClick(){PageMethods.Say("you",funReady,funError);//注意js中調用後台方法的方式} //回呼函數, result 就是後台方法返回的資料function funReady(result){alert(result);}//錯誤處理函數,err 就是後台方法返回的錯誤資訊function funError(err){alert("Error:" + err._message );}</script><asp:ScriptManagerID="ScriptManager1" runat="server"EnablePageMethods="true" /><inputtype="button" onclick="btnClick()" value="test"/>
方法二:
後台方法:
protected string Say(string strCC){strCC = "你好!" + strCC;return strCC;}
前台js:
function Show(){var v = "中國";var s = '<%=Say("'+v+'") %>'; // 你好!“+V+”alert(s);}<input type="button" onclick="Show()" value="提交" />
方法三:
後台方法:
// 需要標識為WebMethod [System.Web.Services.WebMethod]// 注意,要讓前台調用的方法,一定要是public和static的 public static string Say(string name){string result = "Hello:" + name;return result;}
前台js:
<script type="text/javascript">function btnClick(){// 調用頁面後台方法,前面跟方法所需的參數,接著是方法回調成功時要執行的js函數,最後一個是方法回調失敗時要執行的js函數WebSerCustomer.Say("you",function(ress){//ress就是後台方法返回的資料,Say是webservice WebSerCustomer.axms頁面上的方法alert(ress)});} </script><asp:ScriptManager ID="ScriptManager1" runat="server"><Services><asp:ServiceReference Path="~/WebSerCustomer.asmx" /></Services>//WebSerCustomer.asmx後台webservice類的頁名稱</asp:ScriptManager><input type="button" onclick="btnClick()" value="test" />
總結
對於方法一和方法三來說,標識System.web.Services.webmethod可以聲明一個方法可以通過用戶端js函數來調用,並且後台方法必須聲明為public和static,正是由於要將方法聲明為static,使得這兩種方法都有局限性,即靜態方法中只允許訪問靜態成員變數。所以要想用這兩種方式調用後台方法,後台方法中是不能訪問非靜態成員變數的。
對於方法二來說,雖然後台方法沒有任何限制,但是前台調用的時候由於<%=%>是唯讀,前台向後台傳的參數實際上是不存在的,即從後台中拿不到。所以方法二適合於調用後台方法經過處理並返回給用戶端使用,不適合於將資料傳到後台供後台使用。