ajax直接调WCF服务进行数据和逻辑处理
搞了许久,终于配置成功了ajax直接调WCF方法,这种方式我感觉非常精简。
1. HTML:
<html>
<head>
<meta charset="utf-8" />
<title>HelloWorldDemo</title>
<script src="js/jquery-2.1.1.min.js"></script>
</head>
<body>
The server method"SayHello" returned a result:
<span id="displayArea" style="font-weight: bold;"></span>
<script type="text/javascript">
document.onload = Initialize();
function Initialize() {
$.ajax({
type: "get",
url: "http://[这里填写寄托WCF服务的主机ip(使用时去掉中外部括号)]/TestingWeb/MyService.svc/SayHello",
async: true,
dataType: "jsonp",
// 注意,这里不是json,而是jsonp. 如果直接用json则会有跨域问题存在,他们的区别在于:JSON(JavaScript Object Notation)和JSONP(JSON with Padding)虽然只有一个字母的差别,但其实他们根本不是一回事儿:JSON是一种数据交换格式,而JSONP是一种依靠开发人员的聪明才智创造出的一种非官方跨域数据交互协议。 (具体我也不大懂,哟西,先这么用吧,有些东西用着用着某天就理解了。)
// 后记:我记得后来试过,不用jsonp也能行,具体怎么设定的后面会补上,时间比较久了不大记得,之后的文章中会补上的。
success: function(data) {
document.getElementById("displayArea").innerHTML = data.SayHelloResult;
},
error: function(data) {
alert("error occured");
},
complete: function() {
//Do nothing here.
}
});
}
</script>
</body>
</html>
2. WCF: (1). TestingService.csproj:
(2). TestingService.Imp.csproj:
(3). MyService.svc
namespace TestingService {
// NOTE: You can use the "Rename" command on the "Refactor" menu to change the interface name "IMyService" in both code and config file together.
[ServiceContract]
public interface IMyService {
[OperationContract]
[WebInvoke ( Method = "GET", BodyStyle = WebMessageBodyStyle.Wrapped, ResponseFormat = WebMessageFormat.Json )]
string SayHello ();
}
}(2). TestingService.Imp.csproj:
namespace TestingService.Imp {
public class MyServiceProvider : IMyService {
#region IMyService Members
public string SayHello () {
return "Hello, world!";
}
#endregion
}
} (3). MyService.svc
<%@ ServiceHost Language="C#" Debug="true" Service="TestingService.Imp.MyServiceProvider" %>
(4). web.config: (这一段说起来很复杂,建议看不懂的自己去搜WCF服务的配置方法,一般有两种常用托管方式,Windows Service托管方式和IIS托管方式,这里就是IIS托管的方式)
<?xml version="1.0"?>
<!--
For more information on how to configure your ASP.NET application, please visit
-->
<configuration>
<connectionStrings>
<add name="ApplicationServices"
connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\aspnetdb.mdf;User Instance=true"
providerName="System.Data.SqlClient" />
</connectionStrings>
<system.web>
<compilation debug="true" targetFramework="4.0" />
<authentication mode="Forms">
<forms loginUrl="~/Account/Login.aspx" timeout="2880" />
</authentication>
<membership>
<providers>
<clear/>
<add name="AspNetSqlMembershipProvider" type="System.Web.Security.SqlMembershipProvider" connectionStringName="ApplicationServices"
enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false" requiresUniqueEmail="false"
maxInvalidPasswordAttempts="5" minRequiredPasswordLength="6" minRequiredNonalphanumericCharacters="0" passwordAttemptWindow="10"
applicationName="/" />
</providers>
</membership>
<profile>
<providers>
<clear/>
<add name="AspNetSqlProfileProvider" type="System.Web.Profile.SqlProfileProvider" connectionStringName="ApplicationServices" applicationName="/"/>
</providers>
</profile>
<roleManager enabled="false">
<providers>
<clear/>
<add name="AspNetSqlRoleProvider" type="System.Web.Security.SqlRoleProvider" connectionStringName="ApplicationServices" applicationName="/" />
<add name="AspNetWindowsTokenRoleProvider" type="System.Web.Security.WindowsTokenRoleProvider" applicationName="/" />
</providers>
</roleManager>
</system.web>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true"/>
</system.webServer>
<system.serviceModel>
<bindings>
<webHttpBinding>
<binding name="webHttpBindingConfig" crossDomainScriptAccessEnabled="true" />
</webHttpBinding>
</bindings>
<behaviors>
<endpointBehaviors>
<behavior name="webby">
<webHttp defaultBodyStyle="Wrapped" defaultOutgoingResponseFormat="Json" />
</behavior>
</endpointBehaviors>
<serviceBehaviors>
<behavior name="MyServiceBehavior">
<serviceMetadata httpGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="false" />
</behavior>
</serviceBehaviors>
</behaviors>
<serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
<services>
<service behaviorConfiguration="MyServiceBehavior" name="TestingService.Imp.MyServiceProvider">
<endpoint behaviorConfiguration="webby" binding="webHttpBinding"
bindingConfiguration="webHttpBindingConfig" name="webHttpBinding"
contract="TestingService.IMyService" />
<endpoint address="mex" binding="mexHttpBinding" bindingConfiguration=""
name="mexHttpBinding" contract="IMetadataExchange" />
</service>
</services>
</system.serviceModel>
</configuration>
浙公网安备 33010602011771号