ASP.net AJAX 調用PageMethods執行個體(javascript調用伺服器頁面方法)

來源:互聯網
上載者:User

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();
     }
}

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.