如何从ajax上的客户端脚本调用WCF服务 [英] How to call a WCF service from client script on ajax

查看:57
本文介绍了如何从ajax上的客户端脚本调用WCF服务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的服务合约名为IService1,如下所示



My service contract, named IService1, is as follows

using System.ServiceModel;
    using System.ServiceModel.Web;

    namespace WcfServiceDemo
    {
        [ServiceContract]
        public interface IService1
        {
            [OperationContract]
            [WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Json)]
            string GetData(int Value);
        }
    }





这是我的服务实现,



Here's my service implementation,

using System.ServiceModel.Activation;

    namespace WcfServiceDemo
    {
        [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
        public class Service1 : IService1
        {
            public string GetData(int Value)
            {
                return string.Format("You entered: {0}", Value);
            }

        }
    }





我的web.config,





My web.config,

<?xml version="1.0"?>
   <configuration>

     <system.web>
       <compilation debug="true" targetFramework="4.0" />
     </system.web>
     <system.serviceModel>

       <behaviors>
         <serviceBehaviors>
           <behavior name ="ServiceBehavior">
             <!-- To avoid disclosing metadata information, set the value below to false before deployment -->
             <serviceMetadata httpGetEnabled="true"/>
             <!-- To receive exception details in faults for debugging purposes, set the value below to true.  Set to false before deployment to avoid disclosing exception information -->
             <serviceDebug includeExceptionDetailInFaults="false"/>
           </behavior>
         </serviceBehaviors>
         <endpointBehaviors>
           <behavior name="EndPointBehavior">
             <enableWebScript />
           </behavior>
         </endpointBehaviors>
       </behaviors>

       <serviceHostingEnvironment multipleSiteBindingsEnabled="true" />

       <services>
         <service name ="WcfDemoService" behaviorConfiguration="ServiceBehavior">
           <endpoint address="" binding="webHttpBinding" contract="IService1" behaviorConfiguration="EndPointBehavior" />
         </service>
       </services>

     </system.serviceModel>
    <system.webServer>
       <modules runAllManagedModulesForAllRequests="true"/>
       <!--
           To browse web app root directory during debugging, set the value below to true.
           Set to false before deployment to avoid disclosing web app folder information.
         -->
       <directoryBrowse enabled="true"/>
     </system.webServer>

   </configuration>





使用WCF服务的脚本,



Script for consuming WCF service,

<!DOCTYPE html>

    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
        <title></title>
    </head>
    <body>
        <form id="form1" runat="server">
        <div>
            Enter a number:<input type="text" id="txtNum"/>
            <input type="button" onclick="AlertEnteredNum();"/>
        </div>
        </form>
        <script type="text/javascript" src="Script/jquery-1.3.2.min.js"></script>
        <script type="text/javascript">
            function AlertEnteredNum() {
                var Value = $('#txtNum').val();
                $.ajax({
                    type: "POST",
                    contentType: "application/json; charset=utf-8",
                    url: 'Service1.svc/GetData',
                    data: '{"Value": "' + Value + '"}',
                    dataType: "json",
                    processData: false,
                    success: function (data) {
                        alert("Success: " + data.d);
                    },
                    error: function (result) {
                        alert("error: " + result);
                    }
                });
            }
        </script>
    </body>
    </html>





始终错误回调



Always error callback

error: function (result) {
                        alert("error: " + result);
                    }



被执行



我想我需要在IIS上托管,因为我是在我的配置中设置兼容模式。



但是,当我在IIS上托管这个服务时,我得到的解析器错误为targetFramework属性的值无效:'4'。错误:FrameworkName不能少于两个组件或多于三个组件。

参数名称:frameworkName。



任何建议......


gets executed

I think I need to host on IIS, as I am setting compatibility mode in my config.

But, When I host this service on IIS, I am getting parser error as " The value for the targetFramework attribute is invalid: '4'. Error: FrameworkName cannot have less than two components or more than three components.
Parameter name: frameworkName."

Any suggestion...

推荐答案

' #txtNum')。val( );
('#txtNum').val();


.ajax({
type: POST
contentType: application / json; charset = utf-8
url:' Service1.svc / GetData'
data:< span class =code-string>' {Value:' + Value + ' }'
dataType: json
processData: false
成功:函数(数据) {
alert( 成功: + data.d);
},
错误:函数(结果){
alert( 错误: +结果);
}
});
}
< / script >
< / body >
< / html >
.ajax({ type: "POST", contentType: "application/json; charset=utf-8", url: 'Service1.svc/GetData', data: '{"Value": "' + Value + '"}', dataType: "json", processData: false, success: function (data) { alert("Success: " + data.d); }, error: function (result) { alert("error: " + result); } }); } </script> </body> </html>





始终错误回调



Always error callback

error: function (result) {
                        alert("error: " + result);
                    }



被执行



我想我需要在IIS上托管,因为我是在我的配置中设置兼容模式。



但是,当我在IIS上托管这个服务时,我得到的解析器错误为targetFramework属性的值无效:'4'。错误:FrameworkName不能少于两个组件或多于三个组件。

参数名称:frameworkName。



任何建议......


gets executed

I think I need to host on IIS, as I am setting compatibility mode in my config.

But, When I host this service on IIS, I am getting parser error as " The value for the targetFramework attribute is invalid: '4'. Error: FrameworkName cannot have less than two components or more than three components.
Parameter name: frameworkName."

Any suggestion...


最后得到了我的错误&这是解决方案。

只需将配置中的服务元素更改为:



Finally got my mistake & it's solution.
Just needed to change the service element in config as:

<services>
  <service name="WcfServiceDemo.Service1" behaviorconfiguration="ServiceBehavior">
    <endpoint address="" binding="webHttpBinding" contract="WcfServiceDemo.IService1" behaviorconfiguration="EndPointBehavior" />
  </service>
</services>





其中name =WcfServiceDemo.Service1的格式为namespace.ServiceImplementationName& contract =WcfServiceDemo.IService1的格式为namespace.ServiceContractName



where name ="WcfServiceDemo.Service1" is in format "namespace.ServiceImplementationName" & contract="WcfServiceDemo.IService1" is in format "namespace.ServiceContractName"


这篇关于如何从ajax上的客户端脚本调用WCF服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆