有两种方法可实现AJAX调用本地WCF服务,以下使用Jquery实现,具体流程如下:
服务接口 IService1.cs:
namespace wcftest
{
[ServiceContract]
public interface IService1
{
[OperationContract]
string DoWork(string user);
}
}
服务实现 Service1.svc:
namespace wcftest
{
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class Service1 : IService1
{
string IService1.DoWork(string user)
{
return "hello"+user;
}
}
}
Web.config设置:
<system.serviceModel>
<behaviors>
<endpointBehaviors>
<behavior name="test">
<enableWebScript/>
</behavior>
</endpointBehaviors>
</behaviors>
<serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
<services>
<service name="wcftest.Service1">
<endpoint behaviorConfiguration="test" address="" binding="webHttpBinding" contract="wcftest.IService1">
<identity>
<dns value="localhost"/>
</identity>
</endpoint>
</service>
</services>
</system.serviceModel>
前台调用代码:
<script src="jquery-1.3.1.min.js" language="javascript" type="text/javascript"></script>
<body>
<div>
<script type="text/javascript" language="javascript">
function test() {
$.ajax({
type: 'POST',
url: '/Service1.svc/DoWork',
contentType: 'text/json',
data: '{"user":" Beautiful Gril"}',
success: function (msg) {
alert(msg);
}
});
}
</script>
<input id="btnQueryDictionary" type="button" value="调用" onclick="test();" />
</div>
</body>