首先,我说一下如何写一个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必须添加序列化标记
|