BookInfo.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ClassProj
{
[Serializable]
public class BookInfo
{
public BookInfo() { }
//在VS2008中可使用如下簡化方式定義屬性,是不是很簡單了呢?!
public string Name { set; get; }
public string Author { set; get; }
public int Price { set; get; }
}
}Book.asmx.cs
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Xml.Linq;
using System.Web.Script.Services;
using ClassProj;
namespace Test
{
/**//// <summary>
/// Book 的摘要說明
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[ToolboxItem(false)]
// 若要允許使用 ASP.NET AJAX 從指令碼中調用此 Web 服務,請取消對下行的注釋。
[ScriptService]
[GenerateScriptType(typeof(BookInfo))]
public class Book : System.Web.Services.WebService
{
[WebMethod]
public string ShowInfo(BookInfo book)
{
return "書的資訊如下——書名:" + book.Name + ",價格:" + book.Price + "作者:" + book.Author;
}
}
}Test.js
function ShowInfo()
{
var book=new ClassProj.BookInfo();
book.Name="征服AJAX!";
book.Price=25;
book.Author="夢想";
Test.Book.ShowInfo(book,CallBack_Function);
}
function CallBack_Function(ResponseStr)
{
$get("result").innerText=ResponseStr;
}AjaxStudy.aspx.cs
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="AjaxStudy02.aspx.cs" Inherits="Test.AjaxStudy02" %>
<!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>
<body>
<form id="form1" runat="server">
<div>
<asp:ScriptManager ID="ScriptManager1" runat="server">
<Scripts>
<asp:ScriptReference Path="~/JsFile/Test.js" />
</Scripts>
<Services>
<asp:ServiceReference Path="~/Book.asmx" />
</Services>
</asp:ScriptManager>
<input id="Button1" type="button" value="測試一下" onclick="ShowInfo();" />
<div id="result"></div>
</div>
</form>
</body>
</html>