要使用ASP.NET AJAX來呼叫PageMethods,首先必須引入ScriptManager放置於*.aspx頁面<form runat="server">標籤中,並將屬性EnablePageMethods設為true(預設為false),否則執行期將出現PageMethods未被定義的錯誤訊息
接下來將Client端的Javascript修改為
<script language="javascript" type="text/javascript"> function RegisterUsingSingleParameter() { var data = { 'Surname': $get("txtSurname").value, 'GivenName': $get("txtGivenName").value, 'PhoneNumber': $get("txtPhoneNumber").value, 'Address': $get("txtAddress").value }; PageMethods.RegisterUsingSingleParameter(data, SucceedSingleParameter, Fail); } function RegisterUsingMultipleParameters() { PageMethods.RegisterUsingMultipleParameters($get("txtSurname").value, $get("txtGivenName").value, $get("txtPhoneNumber").value, $get("txtAddress").value, SucceedMultipleParameters, Fail); } function SucceedSingleParameter(response) { alert(response.Message); } function SucceedMultipleParameters(response) { alert(response); } function Fail(response) { alert(response.get_message()); } </script>Client端程式碼中的RegisterUsingSingleParameter與RegisterUsingMultipleParameters差別在於前者將要傳遞至Server端的參數封裝在單一變數data中,而後者則是直接多個參數丟給Server端。使用PageMethods.Server端方法名稱(參數1[, 參數2, ..., 參數N], 執行成功回呼函式, 執行失敗回呼函式)即可進行非同步呼叫Server端程式碼;回呼函式的參數response則視Server端回傳的型別而不同,以本篇範例來說,PageMethods.RegisterUsingSingleParameter回呼函式(SucceedSingleParameter)的response為一JSON物件,而PageMethods.RegisterUsingMultipleParameters回呼函式(SucceedMultipleParameters)的response則回傳一字串。
範例程式下載