在園子裡看到很多關於AJAX FOR WCF的文章,大多數採用EXT和WCF互動。
但老實說EXT這個東西比較適合應用開發,對於我這種的網站程式員,EXT比較大。
其中涉及到許多知識點,在這裡和大家分享下。
至於如何使用AJAX FOR WCF我這裡就不說了,園子裡有很多類似的文章:
首先,我說一下如何寫一個JSON傳遞形式調用AJAX FOR WCF服務(我這裡使用JQuery的ajax為例):
$.ajax({
type: 'post',
url: '/TdxGridExample/Wcf/Service.svc/Add', //WCF的URL,/Add是指定該WCF的Add方法
contentType: 'text/json',
data: ’{"x":1,"y":2}‘,
success: function(msg) {
alert(msg);
}
});
註:contentType:類型必須設定為text/json,而不是'text/xml' 或 'text/html'
data,必須是json形式字串:並且要對應後台WCF參數名:
WCF代碼:
[OperationContract]
[WebInvoke(RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, UriTemplate = "/Add", BodyStyle = WebMessageBodyStyle.WrappedRequest)]
public int Add(int x, int y) {
return x + y;
}
{"x":1,"y":2} 中的x對應Add方法中的第一個參數,而y則對應第二個參數:
例2,關於WCF物件類型參數:
js代碼:
function Speak() {
var pople = { p: { name: '張三', sex: 1, birth: JSON2.strToDate('2000-11-11','yyyy-MM-dd')} };
$.ajax({
type: 'post',
url: '/TdxGridExample/Wcf/Service.svc/Speak',
contentType: 'text/json',
data: JSON2.stringify(pople),
success: function(msg) {
alert(msg);
}
});
}
注: wcf的日期類型必須是UTC日期形式的字串類型, 我在JSON2.js 裡擴充了
JSON2.dateFormat('UTC日期格式的字串,例如:/Date(1304179200000+0800)/','日期格式,例如:yyyy-MM-dd');
JSON2.strToDate('2009-11-11','yyyy-MM-dd');
互相轉換的方法。
{ p: { name: '張三', sex: 1, birth: JSON2.strToDate('2000-11-11','yyyy-MM-dd')} }
p 代表下例WCF的Speak方法中參數,
而name,sex,birth 對應People類中的屬性,大小寫必須相符。
wcf代碼:
[ServiceContract(Namespace = "")]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class Service
{
[OperationContract]
[WebInvoke(RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, UriTemplate = "/Add", BodyStyle = WebMessageBodyStyle.WrappedRequest)]
public int Add(int x, int y)
{
return x + y;
}
[OperationContract]
[WebInvoke(RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, UriTemplate = "/Speak", BodyStyle = WebMessageBodyStyle.WrappedRequest)]
public string Speak(People p)
{
string sexCN = p.sex == 1 ? "男" : "女";
return "我叫" + p.name + "," + sexCN + "性,出生於" + p.birth.ToString("yyyy-MM-dd");
}
}
[DataContract]
public class People {
[DataMember]
public string name;
[DataMember]
public byte sex;
[DataMember]
public DateTime birth;
}
註:People必須添加序列化標記
範例程式碼