1.添加新项:启用了Ajax的WCF。
2.[ServiceContract(Namespace = "")]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class Service
{
[OperationContract]
public string DoWork(string str)
{
return str+"!!!";
}
}
3.页面调用
$.ajax({
url: 'Service.svc/DoWork',
data: '{ "str": "sfadasdf" }',
type: 'post',
dataType: 'json',
contentType: 'text/json',
success: function (data) {
if (data.d) {
alert(data.d);
}
},
error: function (xhr) {
alert(xhr.responseText);
}
});
4.传递自定义类型时注意属性要加[DataMember]。
[ServiceContract(Namespace = "")]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class Service
{
[OperationContract]
public Person DoWork(string str)
{
return new Person { Name = str + "!!!" };
}
}
[DataContract]
public class Person
{
[DataMember]
public string Name { get; set; }
}
脚本调用:
alert(data.d.Name);