jQuery调用WCF

jQuery要调用WCF,首先要创建service.svc服务文件,这里边需要注意:

  [ServiceContract(Namespace = "")]
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
    public class WCFservice
    {
        [OperationContract]
        //Post方法,Post方法和Get方法二者只能有一种
        [WebInvoke(RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.WrappedRequest)]
        //Get方法
        //[WebGet(RequestFormat = WebMessageFormat.Json)]
        public string InsertRow(int id,string title,string content)
        {
            return string.Format("您输入的标题是:{0}\n\n您输入的内容是:{1}\n\n此文章的id是:{2}",title,content,id.ToString());
        }
    }

接下来要修改配置文件

<system.serviceModel>
        <behaviors>
            <serviceBehaviors>
                <behavior name="ServiceAspNetAjaxBehavior">
                    <serviceMetadata httpGetEnabled="true" httpGetUrl="" />
                    <serviceDebug httpHelpPageEnabled="true" includeExceptionDetailInFaults="true" />
                </behavior>
            </serviceBehaviors>
            <endpointBehaviors>
                <behavior name="ServiceAspNetAjaxBehavior">
                    <enableWebScript />
                </behavior>
            </endpointBehaviors>
        </behaviors>
        <serviceHostingEnvironment aspNetCompatibilityEnabled="true" />
        <services>
            <service name="jqueryWCF.WCFservice">
                <endpoint address="" behaviorConfiguration="ServiceAspNetAjaxBehavior" binding="webHttpBinding" contract="jqueryWCF.WCFservice" />
            </service>
        </services>
    </system.serviceModel>

前台调用

$.ajax({
        type: 'post',
        url: '/WCFservice.svc/InsertRow',
        contentType: 'text/json',
        data: '{"id":'+id+',"title":"'+title+'","content":"'+content+'","search":"true"}',
        success: function(msg) {
        var a = eval('('+msg+')');
        if(String(a.d).length>0){alert(a.d);}
        else{alert("服务器超时");}
        }
    });
    }

 

posted on 2015-04-16 14:02  狼来了  阅读(292)  评论(0编辑  收藏  举报