1、建立網站,選擇Asp.net Ajax Enabled Web Site 模板()
2、 <asp:scrīptManager ID="scrīptManager1" runat="server"/>中增加 EnablePageMethods="True" ,以啟用PageMethods
3、編寫伺服器端方法代碼
[System.Web.Services.WebMethod]
public static string GetServerTime()
{
return DateTime.Now.ToString();
}
請注意:a、[System.Web.Services.WebMethod]是必須的,相當於ajax.net中的[ajax.method],b、方法前面要上static
4、頁面設計,內容如下
<div>
<input type="button" value="伺服器時間" id="btnGetServerTime" ōnclick="return btnGetServerTime_onclick()" />
<span id="result" />
</div>
5、編寫用戶端javascrīpt
<scrīpt language="javascrīpt" type="text/javascrīpt">
// <!CDATA[
function btnGetServerTime_onclick() {
PageMethods.GetServerTime(cb_getServerTime);
}
function cb_getServerTime(result) {
document.getElementById("result").innerHTML = result;
}
6、執行程式,單擊"伺服器時間" 按鈕就可返回伺服器的時間並顯示在result中。
附:
一、用戶端代完整代碼
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Untitled Page</title>
<scrīpt language="javascrīpt" type="text/javascrīpt">
// <!CDATA[
function btnGetServerTime_onclick() {
PageMethods.GetServerTime(cb_getServerTime);
}
function cb_getServerTime(result) {
document.getElementById("result").innerHTML = result;
}
// ]]>
</scrīpt>
</head>
<body>
<form id="form1" runat="server">
<asp:scrīptManager ID="scrīptManager1" runat="server" EnablePageMethods="True" />
<div>
<input type="button" value="伺服器時間" id="btnGetServerTime" ōnclick="return btnGetServerTime_onclick()" />
<span id="result" />
</div>
</form>
</body>
</html>
二、伺服器端完整代碼
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
public partial class _Default : System.Web.UI.Page
{
[System.Web.Services.WebMethod]
public static string GetServerTime()
{
return DateTime.Now.ToString();
}
}