1. 程式人生 > >js 呼叫後臺程式碼(比較實用,好記)

js 呼叫後臺程式碼(比較實用,好記)

JavaScript呼叫ASP.NET後臺程式碼:  

方法一

1、首先建立一個按鈕,在後臺將呼叫或處理的內容寫入button_click中;  

        2、在前臺寫一個js函式,內容為document.getElementById("btn1").click();  

        3、在前臺或後臺呼叫js函式,激發click事件,等於訪問後臺c#函式;

方法二

        1、函式宣告為public               

           後臺程式碼(把public改成protected也可以)  

           public string methodname()          //注意該方法不能為void,否則執行會報錯

           {  

              //在這之前可以做任何一些服務端的操作,可以不把返回值作為目的,而是要執行一些服務端的程式碼。

              return  "";  
           } 
 
        2、在html裡用<%=fucntion()%>可以呼叫  

           前臺指令碼  

           <script language=javascript>

           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>