第十篇:Ajax調用WCF
好久不更新了,今天寫一寫如何用Ajax調用WCF服務。在WebService時代,隻需要加一行[System.Web.Script.Services.ScriptService]就可以使用Ajax調用了(要求.Net 3.5),到了WCF中,要稍微複雜一些。
寫個小DEMO,這回是基于IIS建一個WCF工程,服務端是一個DataService.svc檔案,用戶端我們自己寫一個Client.htm。
1、服務端
定義服務契約,沒什麼新鮮的,隻有一個GetUser方法。(IDataService.cs)
using System;
using System.ServiceModel;
namespace WebServer
{
[ServiceContract]
public interface IDataService
{
[OperationContract]
User GetUser();
}
}
實作類也超級簡單,傳回一個User對象。(DataService.svc.cs)
public class DataService : IDataService
public User GetUser()
{
return new User { Name = "BoyTNT", Age = 30 };
}
其中的User是資料契約,隻有兩個成員。(User.cs)
using System.Runtime.Serialization;
[DataContract]
public class User
[DataMember]
public string Name { get; set; }
public int Age { get; set; }
然後是重點的Web.config檔案了,要啟用Ajax通路,需要對endpoint進行一下特殊聲明(綠色注釋部分)。下面隻節選了system.serviceModel節點。
<system.serviceModel>
<behaviors>
<serviceBehaviors>
<behavior name="WebServer.DataServiceBehavior">
<serviceMetadata httpGetEnabled="true" />
</behavior>
</serviceBehaviors>
<!--增加一個endpoint的Behavior,命名為AjaxBehavior,為其下加一個enableWebScript節點,表示允許使用腳本通路-->
<endpointBehaviors>
<behavior name="AjaxBehavior">
<enableWebScript/>
</endpointBehaviors>
</behaviors>
<services>
<service behaviorConfiguration="WebServer.DataServiceBehavior" name="WebServer.DataService">
<!--使用webHttpBinding,并且标明使用上面定義的AjaxBehavior-->
<endpoint address="" binding="webHttpBinding" contract="WebServer.IDataService" behaviorConfiguration="AjaxBehavior" />
</service>
</services>
</system.serviceModel>
2、用戶端
在工程裡加一個Client.htm,注意ajax請求不能跨域,是以必須和服務端放到一塊兒。我這裡使用了jquery來進行ajax通路。
<!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>
<title>接口測試程式</title>
<script language="javascript" src="jquery-1.4.2.js"></script>
<script language="javascript">
function executeAjaxQuery() {
$.ajax({
"url": "DataService.svc/GetUser", //注意通路的url的寫法,是服務名+方法名,這點和WebService是一緻的
"cache": false,
"async": true,
"type": "POST",
"dataType": "json",
"contentType": "application/json; charset=utf-8",
"data": {}, //如果有參數,在這裡傳遞
success: function (json) {
//結果被封裝到json.d屬性中,資料契約中定義的兩個成員都能取到
$("#result").val("Name=" + json.d.Name + ", Age=" + json.d.Age);
},
error: function (x, e) {
$("#result").val(x.responseText);
}
});
}
</script>
</head>
<body>
<input type="button" value="擷取使用者" onclick="executeAjaxQuery()" /><br />
<textarea id="result" style="width:400px;height:200px"></textarea>
</body>
</html>
OK,運作一下,在結果視窗裡應該能收到“Name=BoyTNT, Age=30”。如果抓一下包,能看到服務端傳回的内容是:
{"d":{"__type":"User:#WebServer","Age":30,"Name":"BoyTNT"}}
這就是為什麼要從json.d中取資料的原因。
本文轉自 BoyTNT 51CTO部落格,原文連結:http://blog.51cto.com/boytnt/857350,如需轉載請自行聯系原作者