一般的ajax程序是HTML+ASHX,要寫很多通信代碼,但是微軟的WCF集成了通信代碼,簡化了代碼.
1,新建一個WCF服務器頁面,新建一個給客戶端使用的方法,及數據類.
using System;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Activation;
using System.ServiceModel.Web;
namespace WebApplication1
{
[ServiceContract(Namespace = "")]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class WCFService1
{
/// <summary>
/// 獲取用戶信息
/// </summary>
/// <param name="id">用戶id</param>
/// <returns>存放用戶信息的用戶類</returns>
[OperationContract]
public user GetUser(int id) {
return new user() {username="小江",age=22,address="浙江溫州" };
}
// 添加 [WebGet] 屬性以使用 HTTP GET
[OperationContract]
public void DoWork()
{
// 在此處添加操作實現
return;
}
// 在此處添加更多操作並使用 [OperationContract] 標記它們
}
/// <summary>
/// 定義用戶類,存放用戶數據
/// </summary>
public class user
{
public string username { get; set; }
public int age { get; set; }
public string address { get; set; }
}
}
2,添加一個aspx頁面,在頁面頂部添加一個ScriptManager控件,在這個控件的數據集裏添加服務器頁面進來,
最後寫js代碼,直接像寫C#程序一樣寫js代碼,很方便.
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WCFAjax.aspx.cs" Inherits="WebApplication1.WCFAjax" %>
<!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>
<style type="text/css">
#Text3
{
height: 50px;
width: 181px;
}
</style>
<script type="text/javascript">
function $(id) { return document.getElementById(id); }
function Button1_onclick() {
WCFService1.GetUser(1, function(data) {//調用服務器Getuser(id,fn,fn)方法,第一個爲參數,第二個爲返回成功的匿名函數,第三個爲返回失敗的匿名函數
$("Text1").value = data.username;
$("Text2").value = data.age;
$("Text3").value = data.address;
}, function() { alert("獲取失敗"); });
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<p>
<asp:ScriptManager ID="ScriptManager1" runat="server">
<Services>
<asp:ServiceReference Path="~/WCFService1.svc" />
</Services>
</asp:ScriptManager>
用戶名<input id="Text1" type="text" /></p>
<p>
年齡<input id="Text2" type="text" /></p>
<p>
地址<input id="Text3" type="text" /></p>
<p>
<input id="Button1" type="button" value="button" οnclick="return Button1_onclick()" /></p>
</div>
</form>
</body>
</html>