有两种方法可实现AJAX调用本地WCF服务,以下使用ScriptManager控件实现.
通过微软的ScriptManager控件,具体流程如下:
服务接口 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>
前台调用代码:
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server">
<Services>
<asp:ServiceReference Path="~/Service1.svc" />
</Services>
</asp:ScriptManager>
<div>
<input id="btnQueryDictionary" type="button" value="调用" onclick="btnClick();" />
</div>
</form>
</body>
<script language="javascript" type="text/javascript">
function btnClick()
{
var user = " Beautiful Gril";
var wcfProxy = new tempuri.org.IService1();
wcfProxy.DoWork(user, OnSucceededCallback, OnFailedCallback);
}
function OnSucceededCallback(result, userContext, methodName)
{
if (methodName == "DoWork")
{
alert(result);
}
}
function OnFailedCallback(error, userContext, methodName)
{
alert("异常信息:" + error.get_message());
}
</script>