您的位置:首页 > Web前端 > JQuery

基于JQUERY调用WCF服务的使用和记录

2011-04-20 22:33 633 查看
WebConfig serviceModel配置方法一:

<system.serviceModel>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true">
<serviceActivations>
<add relativeAddress="HelloService.svc" service="HelloService"
factory="System.ServiceModel.Activation.WebScriptServiceHostFactory"/>
</serviceActivations>
</serviceHostingEnvironment>
</system.serviceModel>

WebConfig serviceModel配置方法二:

<system.serviceModel>
<behaviors>
<endpointBehaviors>
<behavior name="AllenBehavior">
<enableWebScript />
</behavior>
</endpointBehaviors>
</behaviors>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" />
<services>
<service name="HelloService">
<endpoint address="" behaviorConfiguration="AllenBehavior" binding="webHttpBinding" contract="HelloService" />
</service>
</services> </system.serviceModel>

添加属性取消asp.net兼容性模式的限制:

[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]

其中<service>节点中的name属性,是实现了服务契约的类型名,类型名必须是完整的,要包括名称空间
<endpoint>节点的address属性为空,说明使用基地址.
behaviorConfiguration属性与behavior节点的name属性相匹配
binding属性说明WCF服务使用什么协议,这里是HTTP协议
contract属性是描述契约的接口名称,也必须是完整的.如果没有接口直接写实现契约的类型名也可以(我这里就是这样).

<behavior>节点的信息是描述WCF服务端的一些特性,行为的<behavior name="AllenBehavior"> name属性与前面说的behaviorConfiguration属性一致
<enableWebScript />节点使我们的WCF支持ajax
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" />与后端的AspNetCompatibilityRequirements配合使用

<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.5.1.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
$("#ibOk").bind("click", function () {
var param = $("#ipText").val();
$.ajax({
url: "HelloService.svc/Say",
type: "POST",
dataType: 'json',
//WebService中这样写:"application/json; charset=utf-8"
contentType: 'text/json',
//WebService中这样写:'{word:"Hello, world"}'
data: '{"word":"' + param + '"}',
success: function (data) {
alert(data.d.toString());
},
error: function (erro) {
alert(erro.responseText);
}
});
})
});
</script>
</asp:Content>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
<input type="text" name="name" id="ipText" />
<input type="button" value="提交" id="ibOk" />

url: '/HelloService.svc/Say
这里是WCF的地址+方法名

contentType: 'text/json',这是以JSON的方式POST数据,当然也可以用XML的方式(要配合WCF后端的定义)

data: '{"id":'+id+',"title":"'+title+'","content":"'+content+'"}',数据必须按照方法的签名传递(这里稍有不慎就出错了,而且js的调试比较难搞)

RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json
说明传递近来的数据都是JSON形式的,只有两种形式,一个是JSON,一个是XML.
(我觉得JSON更"对象"一点,XML更"数据"一点)

BodyStyle = WebMessageBodyStyle.WrappedRequest是把参数包装一下,这样可以传递多个参数进来, 如何控制缓存,比如:如何在WCF返回时设置Expires Header和If-Modified-Since,避免频繁的WCF调用。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: