天天看點

VS2005 使用AJAX直接調用背景方法

首先都是使用VS.Net2005建立一個 ASP.Net AJAX-Enabled Web Application

 1、使用AJAX直接調用背景方法:

背景代碼:

namespace AJAX1

{

    public partial class _Default : System.Web.UI.Page

    {

        // 需要辨別為WebMethod 

        [System.Web.Services.WebMethod]

        // 注意,要讓前台調用的方法,一定要是public和static的 

        public static string Hello(string name)

        {

            return "Hello:" + name;

        }

    }

}

前台代碼:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="AJAX1._Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >

<head runat="server">

    <title>Untitled Page</title>

    <script type="text/javascript">

        function btnClick(){

            // 調用頁面背景方法,前面跟方法所需的參數,接着是方法回調成功時要執行的js函數,最後一個是方法回調失敗時要執行的js函數

            PageMethods.Hello("you",funReady,funError);

        }        

        // result 就是背景方法傳回的資料

        function funReady(result){

            alert(result);

        }

        // err 就是背景方法傳回的錯誤資訊

        function funError(err){

            alert("Error:" + err._message );

        }

    </script>

</head>

<body>

    <form id="form1" runat="server">

    <div>

        下面要加上EnablePageMethods="true"屬性,才能使用背景方法        

        <asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true">

        </asp:ScriptManager>

        <input type="button" οnclick="btnClick();" value="test" />

    </div>

    </form>

</body>

</html>

繼續閱讀