js 調用後臺代碼(比較實用,好記)

 
 

JavaScript調用ASP.NET後臺代碼:  

方法一javascript

        一、首先創建一個按鈕,在後臺將調用或處理的內容寫入button_click中;  html

        二、在前臺寫一個js函數,內容爲document.getElementById("btn1").click();  前端

        三、在前臺或後臺調用js函數,激發click事件,等於訪問後臺c#函數;

方法二java

        一、函數聲明爲public               c#

           後臺代碼(把public改爲protected也能夠)  ssh

           public string methodname()          //注意該方法不能爲void,不然執行會報錯            {  

              //在這以前能夠作任何一些服務端的操做,能夠不把返回值做爲目的,而是要執行一些服務端的代碼。函數

              return  "";              }            二、在html裏用<%=fucntion()%>能夠調用  

           前臺腳本  spa

           <script language=javascript>htm

           var a = "<%=methodname()%>";  

           alert(a); 事件

           eval("<%=methodname()%>");     //若是隻是要執行服務端的一些代碼也能夠寫爲以下,這樣就能夠執行服務端代碼了

           </script>
方法三:利用PageMethods調用後臺代碼
PageMethod方法介紹:
PageMethods.FunctionName(Paramter1,Parameter2,...,SuccessMethod, FailedMethod, userContext); 其中,前面Paramter1,Parameter2,...,表示的是FunctionName的參數,類型是Object或Array; SuccessMethod是須要使用後臺返回結果的Js方法, FailedMethod是當後臺的csFunctionName方法發生異常狀況下的執行的Js方法(容錯處理方法), userContext是能夠傳遞給SuccessMethod方法,或是FailedMethod方法的任意內容。
實現方法三按照如下步驟:

1.在後臺建立方法,必須是static(靜態的),方法必須是public類型的,不然訪問不到會報異常,

接着要在該方法頭部上加上[System.Web.Services.WebMethod],來標註方法特性。

2.在前臺頁面加入ScriptManager控件,並把其EnablePageMethods屬性設爲true。

3.調用PageMethods,因爲該方法有不少重載,如今只說最簡單的實現。

PageMethods.FunctionName(回調的js方法);      //其中FunctionName爲後臺建立的靜態方法名,回調js方法爲前臺接受結果的方法。

 

PageMethods例子:

 

後臺代碼:

一.無參數方法

 [System.Web.Services.WebMethod]     public static string ShowValue()     {         return "js調用後臺方法";     }

二.有參數方法

[System.Web.Services.WebMethod]     public static string ShowValue2(string msg)     {         return msg;

    }

 

前端代碼:

 <script type="text/javascript">  

       //調用後臺無參數方法

        function bclick()         {             PageMethods.ShowValue(sshow);         }                  function sshow(val)       //回傳方法用val接受後臺代碼ShowValue的執行結果         {             document.getElementById("show").innerText = val;

        }

        //調用後臺有參數方法

        function bclick2()         {              var text = "test";              PageMethods.ShowValue2(text,sshow2);         }                  function sshow2(val)       //回傳方法用val接受後臺代碼ShowValue的執行結果         {             document.getElementById("show").innerText = val;         }  </script>   < input id="Button1" type="button" value="click" onclick="bclick();" /> < input id="Button2" type="button" value="click2" onclick="bclick2();" /> < div id="show"></div>
相關文章
相關標籤/搜索