首先要考虑的是same origin policy 限制。如果您无法遵守它,并且您的 Web 服务与使用 AJAX 脚本的域不同,您可能会停止阅读我的答案并重新考虑您的架构。
如果您仍在阅读,您可以像往常一样从定义服务合同和实施开始:
[ServiceContract]
public interface IFoo
{
[OperationContract]
string GetData(int value);
}
public class FooService : IFoo
{
public string GetData(int value)
{
return string.Format("You entered: {0}", value);
}
}
然后添加一个fooservice.svc 文件,它将在 IIS 中公开服务:
<%@ ServiceHost
Language="C#"
Debug="true"
Service="SomeNs.FooService"
CodeBehind="FooService.svc.cs"
Factory="System.ServiceModel.Activation.WebScriptServiceHostFactory"
%>
最后一行 Factory="System.ServiceModel.Activation.WebScriptServiceHostFactory" 非常重要,因为这将允许您使用 JSON。
最后一部分是web.config:
<system.serviceModel>
<behaviors>
<serviceBehaviors>
<behavior>
<serviceMetadata httpGetEnabled="true"/>
<serviceDebug includeExceptionDetailInFaults="false"/>
</behavior>
</serviceBehaviors>
</behaviors>
<serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
</system.serviceModel>
最后是一个发送 AJAX 请求来使用服务的 HTML 页面:
<!DOCTYPE html>
<html>
<head>
<title>WCF Test</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript" src="http://www.json.org/json2.js"></script>
<script type="text/javascript">
$(function () {
$.ajax({
// Notice the URL here: Need to be hosted on the same domain
url: '/fooservice.svc/getdata',
type: 'post',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify({ value: 7 }),
success: function (result) {
alert(result.d);
}
});
});
</script>
</head>
<body>
</body>
</html>