方式1- PageMethods
頁面上Scriptmanager需要設定EnablePageMethods=true
[System.Web.Services.WebMethod] public static string get_some_text() { return "hi"; }
function call_function{ alert(PageMethods.get_some_text()); }
後端程式碼需要加上屬性[System.Web.Services.WebMethod]並且宣告方法為static。
方法2-__doPostBack
如果不是要求非同步作業或是返回值,可以有個更為簡便的方式來實現。
function call_function(){ __doPostBack('control_id',''); }
在頁面上可以插入個control(LinkButton、Button等),上方的Javascript就會呼叫該控制項的OnClick事件,將要實現的功能寫在該事件內即可。