aspx:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="PriceSystem_temp_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></title>
</head>
<script src="../js/jquery-1.5.1.min.js" type="text/javascript"></script> 1:
2:
3: <script>
4: $(function() { 5: PageMethods.Hello("張三", function(e) { 6: alert(e);
7: });
8: })
</script>
<body>
<form id="form1" runat="server">
<asp:scriptmanager ID="Scriptmanager1" EnablePageMethods="true" runat="server"></asp:scriptmanager>
<div>
</div>
</form>
</body>
</html>
cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Xml;
using System.Xml.XPath;
using System.Xml.Linq;
using System.Data;
using System.Web.Services;
public partial class PriceSystem_temp_Default : PageBase
{
protected void Page_Load(object sender, EventArgs e)
{
}
[WebMethod(EnableSession = true)]
public static string Hello(string name)
{
return "hello," + name;
}
}
總結ASP.NET AJAX在用戶端JavaScript中非同步呼叫伺服器端Web Service,我們需要: 1 為Web Service類或需要暴露給用戶端的Web Service方法添加[ScriptService]屬性; 2 為Web Service中需要暴露給用戶端的方法添加[WebMethod]屬性; 3 在頁面中的ScriptManager控制項中添加對該Web Service的引用; 4 在用戶端使用如下JavaScript文法調用該Web Service: [NameSpace].[ClassName].[MethodName](param1, param2,..., callbackFunction) 5 為用戶端非同步呼叫指定回呼函數,在回呼函數中接收傳回值並進一步處理。使用ASP.NET AJAX在用戶端JavaScript中非同步呼叫定義在ASP.NET頁面中的方法,我們需要: 1 將該方法聲明為公有(public); 2 將該方法聲明為類方法(C#中的static,VB.NET中的Shared),而不是執行個體方法; 3 為該方法添加[WebMethod]屬性; 4 將頁面中ScriptManager控制項的EnablePageMethods屬性設定為true; 5 在用戶端使用如下JavaScript文法調用該頁面方法: PageMethods.[MethodName](param1, param2,..., callbackFunction); 6 為用戶端非同步呼叫指定回呼函數,在回呼函數中接收傳回值並進一步處理