ajax调用WCF服务

6 篇文章 0 订阅

来自:http://blog.csdn.net/zx13525079024/article/details/7358223

关于AJAX调用WCF服务分为跨域和不跨域两种方式,今天咱们先介绍下不跨域下的调用方法。DEMO是在VS2008写的.

经过测试与研究,发现AJAX调用WCF服务必须满足以下条件

1.wcf的通讯方式必须使用webHttpBinding

2.必须设置<endpointBehaviors>节点的值

3.服务的实现必须添加

[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)] 标记

4.方法前面必须添加如下标记

[WebInvoke(Method = "POST", BodyStyle = WebMessageBodyStyle.Bare, ResponseFormat = WebMessageFormat.Json)]

5.ajax方法中传递的参数名称必须和wcf服务中提供的参数方法名称一致

以下是本人写的代码,标记颜色的是需要注意的地方

服务器端配置文件代码

  1. <system.serviceModel>
  2. <services>
  3. <service name="WcfServiceDemoOne.Service1" behaviorConfiguration="WcfServiceDemoOne.Service1Behavior">
  4. <!-- Service Endpoints -->
  5. <endpoint address="" binding="webHttpBinding" contract="WcfServiceDemoOne.IService1" behaviorConfiguration="HttpBehavior"></endpoint>
  6. <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
  7. <host>
  8. <baseAddresses>
  9. <add baseAddress="http://localhost:12079/Service1.svc"/>
  10. </baseAddresses>
  11. </host>
  12. </service>
  13. </services>
  14. <behaviors>
  15. <serviceBehaviors>
  16. <behavior name="WcfServiceDemoOne.Service1Behavior">
  17. <!-- 为避免泄漏元数据信息,请在部署前将以下值设置为 false 并删除上面的元数据终结点-->
  18. <serviceMetadata httpGetEnabled="true"/>
  19. <!-- 要接收故障异常详细信息以进行调试,请将以下值设置为 true。在部署前设置为 false 以避免泄漏异常信息-->
  20. <serviceDebug includeExceptionDetailInFaults="false"/>
  21. </behavior>
  22. </serviceBehaviors>
  23. <endpointBehaviors>
  24. <behavior name="HttpBehavior">
  25. <webHttp/>
  26. </behavior>
  27. </endpointBehaviors>
  28. </behaviors>
  29. </system.serviceModel>
<system.serviceModel>
		<services>
			<service name="WcfServiceDemoOne.Service1" behaviorConfiguration="WcfServiceDemoOne.Service1Behavior">
				<!-- Service Endpoints -->
        <endpoint address="" binding="webHttpBinding" contract="WcfServiceDemoOne.IService1"  behaviorConfiguration="HttpBehavior"></endpoint>

				<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
				<host>
					<baseAddresses>
						<add baseAddress="http://localhost:12079/Service1.svc"/>
					</baseAddresses>
				</host>
			</service>
		</services>
		<behaviors>
			<serviceBehaviors>
				<behavior name="WcfServiceDemoOne.Service1Behavior">
					<!-- 为避免泄漏元数据信息,请在部署前将以下值设置为 false 并删除上面的元数据终结点-->
					<serviceMetadata httpGetEnabled="true"/>
					<!-- 要接收故障异常详细信息以进行调试,请将以下值设置为 true。在部署前设置为 false 以避免泄漏异常信息-->
					<serviceDebug includeExceptionDetailInFaults="false"/>
				</behavior>
			</serviceBehaviors>

      <endpointBehaviors>
        <behavior name="HttpBehavior">
          <webHttp/>
        </behavior>
      </endpointBehaviors>
		</behaviors>
	</system.serviceModel>



服务器端代码

  1. [ServiceContract]
  2. public interface IService1
  3. {
  4. [OperationContract]
  5. string GetData(int value);
  6. [OperationContract]
  7. City GetDataUsingDataContract(City composite);
  8. [OperationContract]
  9. List<City> GetList();
  10. [OperationContract]
  11. List<City> GetListData(List<City> list);
  12. }
  13. // 使用下面示例中说明的数据约定将复合类型添加到服务操作。
  14. [DataContract]
  15. public class City
  16. {
  17. int seq = 0;
  18. string cityID;
  19. string ctiyName;
  20. [DataMember]
  21. public string CityID
  22. {
  23. get
  24. {
  25. return cityID;
  26. }
  27. set
  28. {
  29. cityID=value;
  30. }
  31. }
  32. [DataMember]
  33. public string CityName
  34. {
  35. get { return ctiyName; }
  36. set { ctiyName = value; }
  37. }
  38. [DataMember]
  39. public int Seq
  40. {
  41. get
  42. { return seq; }
  43. set
  44. { seq = value; }
  45. }
  46. }
[ServiceContract]
    public interface IService1
    {

        [OperationContract]
        string GetData(int value);

        [OperationContract]
        City GetDataUsingDataContract(City composite);

         [OperationContract]
        List<City> GetList();

         [OperationContract]
        List<City> GetListData(List<City> list);
    }


    // 使用下面示例中说明的数据约定将复合类型添加到服务操作。
    [DataContract]
    public class City
    {
        int seq = 0;
        string cityID;
        string ctiyName;
        
         [DataMember]
        public string CityID
        {
           get
           {
               return cityID;
           }
            set
            {
              cityID=value;
            }
        }

        [DataMember]
        public string  CityName
        {
            get { return ctiyName; }
            set { ctiyName = value; }
        }

        [DataMember]
        public int Seq
        {
            get
            { return seq; }
            set
            { seq = value; }
        }
    }


实现代码

  1. [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
  2. public class Service1 : IService1
  3. {
  4. [WebInvoke(Method = "POST", BodyStyle = WebMessageBodyStyle.WrappedRequest, RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
  5. public string GetData(int value)
  6. {
  7. return string.Format("You entered: {0}", value);
  8. }
  9. #region IService1 成员
  10. [WebInvoke(Method = "POST", BodyStyle = WebMessageBodyStyle.Bare, ResponseFormat = WebMessageFormat.Json)]
  11. public City GetDataUsingDataContract(City composite)
  12. {
  13. City c = new City();
  14. c.CityID = composite.CityID;
  15. c.CityName = composite.CityName;
  16. c.Seq = composite.Seq;
  17. return c;
  18. }
  19. [WebInvoke(Method = "POST", BodyStyle = WebMessageBodyStyle.Bare, ResponseFormat = WebMessageFormat.Json)]
  20. public List<City> GetList()
  21. {
  22. List<City> list = new List<City>();
  23. City cc = new City();
  24. cc.CityID = "1";
  25. cc.CityName="北京";
  26. cc.Seq = 3;
  27. list.Add(cc);
  28. City cc1 = new City();
  29. cc1.CityID = "2";
  30. cc1.CityName = "上海";
  31. cc1.Seq = 4;
  32. list.Add(cc1);
  33. return list;
  34. }
  35. [WebInvoke(Method = "POST", BodyStyle = WebMessageBodyStyle.Bare, ResponseFormat = WebMessageFormat.Json)]
  36. public List<City> GetListData(List<City> list)
  37. {
  38. return list;
  39. }
  40. #endregion
  41. }
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
    public class Service1 : IService1
    {
        [WebInvoke(Method = "POST", BodyStyle = WebMessageBodyStyle.WrappedRequest, RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
        public string GetData(int value)
        {
            return string.Format("You entered: {0}", value);
        }

        #region IService1 成员

        [WebInvoke(Method = "POST", BodyStyle = WebMessageBodyStyle.Bare, ResponseFormat = WebMessageFormat.Json)]
        public City GetDataUsingDataContract(City composite)
        {
            City c = new City();
            c.CityID = composite.CityID;
            c.CityName = composite.CityName;
            c.Seq = composite.Seq;
            return c;
        }

        [WebInvoke(Method = "POST", BodyStyle = WebMessageBodyStyle.Bare, ResponseFormat = WebMessageFormat.Json)]
        public List<City> GetList()
        {
            List<City> list = new List<City>();
            City cc = new City();
            cc.CityID = "1";
            cc.CityName="北京";
            cc.Seq = 3;
            list.Add(cc);

            City cc1 = new City();
            cc1.CityID = "2";
            cc1.CityName = "上海";
            cc1.Seq = 4;
            list.Add(cc1);
            return list;
        }

        [WebInvoke(Method = "POST", BodyStyle = WebMessageBodyStyle.Bare, ResponseFormat = WebMessageFormat.Json)]
        public List<City> GetListData(List<City> list)
        {
            return list;
        }

        #endregion
    }


客户端调用代码

  1. <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WcfServiceDemoOne.WebForm1" %>
  2. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  3. <html xmlns="http://www.w3.org/1999/xhtml" >
  4. <head runat="server">
  5. <title></title>
  6. <script src="jquery-1.7.1.min.js" type="text/javascript"></script>
  7. <script type="text/javascript">
  8. //参数为整数的方法
  9. function fn1()
  10. {
  11. $.ajax({
  12. url: "http://localhost:12079/Service1.svc/GetData",
  13. type: "POST",
  14. contentType: "text/json",
  15. data: '{"value":2}',
  16. dataType: "json",
  17. success: function(returnValue) {
  18. alert(returnValue);
  19. },
  20. error: function() {
  21. alert('error');
  22. }
  23. });
  24. }
  25. //参数为实体类的方法
  26. function fn2() {
  27. $.ajax({
  28. url: "http://localhost:12079/Service1.svc/GetDataUsingDataContract",
  29. type: "POST",
  30. contentType: "application/json",
  31. data: '{"CityID":1,"CityName":"北京","Seq":"3"}',
  32. dataType: "json",
  33. success: function(returnValue) {
  34. alert(returnValue.CityID + ' ' + returnValue.CityName + "--" + returnValue.Seq);
  35. },
  36. error: function() {
  37. alert('error');
  38. }
  39. });
  40. }
  41. //返回值为类集合的方法
  42. function fn3() {
  43. $.ajax({
  44. url: "http://localhost:12079/Service1.svc/GetList",
  45. type: "POST",
  46. contentType: "application/json",
  47. dataType: "json",
  48. success: function(returnValue) {
  49. for (var i = 0; i < returnValue.length; i++) {
  50. alert(returnValue[i].CityID + ' ' + returnValue[i].CityName+'---'+returnValue[i].Seq);
  51. }
  52. },
  53. error: function() {
  54. alert('error');
  55. }
  56. });
  57. }
  58. function fn4() {
  59. $.ajax({
  60. url: "http://localhost:12079/Service1.svc/GetListData",
  61. type: "POST",
  62. contentType: "application/json",
  63. data: '[{"CityID":1,"CityName":"北京","Seq":"3"},{"CityID":3,"CityName":"上海","Seq":"3"}]',
  64. dataType: "json",
  65. success: function(returnValue) {
  66. for (var i = 0; i < returnValue.length; i++) {
  67. alert(returnValue[i].CityID + ' ' + returnValue[i].CityName + '---' + returnValue[i].Seq);
  68. }
  69. },
  70. error: function() {
  71. alert('error');
  72. }
  73. });
  74. }
  75. </script>
  76. </head>
  77. <body>
  78. <form id="form1" runat="server">
  79. <div>
  80. <input id="Button1" type="button" value="调用1" onclick="fn1();" /></div>
  81. <input id="Button2" type="button" value="调用2" onclick="fn2();" />
  82. <br />
  83. <input id="Button3" type="button" value="调用3" onclick="fn3();" /></form>
  84. <br />
  85. <input id="Button4" type="button" value="调用4" onclick="fn4();"/>
  86. </body>
  87. </html>
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WcfServiceDemoOne.WebForm1" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title></title>
    <script src="jquery-1.7.1.min.js" type="text/javascript"></script>
    <script type="text/javascript">
    //参数为整数的方法
       function fn1()
       {
           $.ajax({
           url: "http://localhost:12079/Service1.svc/GetData",
               type: "POST",
               contentType: "text/json",
               data: '{"value":2}',
               dataType: "json",
               success: function(returnValue) {
                   alert(returnValue);
               },
               error: function() {
                   alert('error');
               }
           });

       }

//参数为实体类的方法
       function fn2() {
           $.ajax({
           url: "http://localhost:12079/Service1.svc/GetDataUsingDataContract",
               type: "POST",
               contentType: "application/json",
               data: '{"CityID":1,"CityName":"北京","Seq":"3"}',
               dataType: "json",
               success: function(returnValue) {
               alert(returnValue.CityID + '  ' + returnValue.CityName + "--" + returnValue.Seq);
               },
               error: function() {
                   alert('error');
               }
           });
       }

//返回值为类集合的方法
       function fn3() {
           $.ajax({
               url: "http://localhost:12079/Service1.svc/GetList",
               type: "POST",
               contentType: "application/json",
               dataType: "json",
               success: function(returnValue) {
               for (var i = 0; i < returnValue.length; i++) {
                   alert(returnValue[i].CityID + '  ' + returnValue[i].CityName+'---'+returnValue[i].Seq);
                   }
               },
               error: function() {
                   alert('error');
               }
           });

       }

       function fn4() {
           $.ajax({
           url: "http://localhost:12079/Service1.svc/GetListData",
               type: "POST",
               contentType: "application/json",
               data: '[{"CityID":1,"CityName":"北京","Seq":"3"},{"CityID":3,"CityName":"上海","Seq":"3"}]',
               dataType: "json",
               success: function(returnValue) {
               for (var i = 0; i < returnValue.length; i++) {
                   alert(returnValue[i].CityID + '  ' + returnValue[i].CityName + '---' + returnValue[i].Seq);
               }
               },
               error: function() {
                   alert('error');
               }
           });
       }
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    
        <input id="Button1" type="button" value="调用1" οnclick="fn1();" /></div>
        <input id="Button2" type="button" value="调用2" οnclick="fn2();" />
        <br />
    <input id="Button3" type="button" value="调用3" οnclick="fn3();" /></form>
    <br />
    <input id="Button4" type="button" value="调用4"  οnclick="fn4();"/>
    
</body>
</html>


demo下载地址:

http://download.csdn.net/detail/zx13525079024/4144097


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值