首先建立 WCF 服務,程式碼很簡單:
using System;
using System.Data;
using System.ServiceModel;
using System.ServiceModel.Activation;
using System.ServiceModel.Web;
using System.Web.Script.Services;
[ServiceContract(Namespace = "")]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
[ServiceBehavior(IncludeExceptionDetailInFaults = true)]
public class imgService
{
[OperationContract]
[WebGet(RequestFormat=WebMessageFormat.Json, ResponseFormat=WebMessageFormat.Json)]
public DataTable GetDataTable(string pz)
{
DataSet ds = WebBase.GetDS(WebBase.meinvRepository, string.Empty, " body_id desc", pz);
if (ds.Tables.Count > 0)
return ds.Tables[0];
return null;
}
}
此 WCF 只有一個 GetDataTable 方法,參數 pz 表示回傳的資料行數,回傳的 DataTable 以 JSON 形式供 jQuery 使用。
<script type="text/javascript">
function sendAJAX(data) {
var url = "<%=_url %>imgService.svc/GetDataTable";
$.getJSON(url, { pz: "6" }, function (msg) {
$(msg.d).find("Table").each(function (i) {
var rq = $(this).children("Body_AddTime").text().split('T')[0].replace("-", "").replace("-", "");
rq = rq.substring(0, rq.length - 2);
var html = '<li><a href="..." target="_blank"><img src="..." />' + $(this).children("Body_Name").text() + '</a></li>';
$(".main ul").append(html);
});
});
}
$(function () { sendAJAX(); });
</script>
重點是透過 jQuery 的 getJSON 方法取得 WCF 回傳的資料,傳參方式為 $.getJSON(url, { pz: "6" }, function(msg){ ... }),這裡代表取回 6 筆資料。此外,.svc 檔需加上 Factory=System.ServiceModel.Activation.WebScriptServiceHostFactory 屬性,並在 web.config 中正確設定 serviceHostingEnvironment、endpoints(binding="webHttpBinding"、behaviorConfiguration 啟用 enableWebScript)等節點。
設定完成後即可成功以 Ajax 方式呼叫 WCF 並將資料呈現在頁面上。