wcf4实现跨域访问(转)

这个例子是在网上找的,但是找不到原来的出处了。

主要代码如下,.svc.cs代码:

    [ServiceContract(Namespace = "")]
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
    //UrlParameterName is the jsonp callback name in the request url.
    [JavascriptCallbackBehavior(UrlParameterName = "jsoncallback")]
    public class JSONP
    {
        [OperationContract]
        [WebGet(ResponseFormat = WebMessageFormat.Json)]
        public string JsonPHelloWorld()
        {
            return "Hello World";
        }

        [OperationContract]
        [WebGet(ResponseFormat = WebMessageFormat.Json)]
        public string settingInterval(string UserName, int Interval)
        {

            string flag = new SaveIntervalInfo2SQL().SaveInfo(UserName, Interval);
            return flag;
        }
     }

在web.config中要注意添加:

<system.serviceModel>
    <behaviors>

      <endpointBehaviors>
        <behavior name="DebugSite.JSONPAspNetAjaxBehavior">
          <enableWebScript />
        </behavior>
      </endpointBehaviors>

      <serviceBehaviors>
        <behavior name="EnableMetadataBehaviors">
          <serviceMetadata httpGetEnabled="true" />
          <serviceDebug includeExceptionDetailInFaults="true" />
        </behavior>
      </serviceBehaviors>
    </behaviors>


    <bindings>
      <webHttpBinding>
        <!--crossDomainScriptAccessEnabled make the WCF 4 service support the JSONP-->
        <binding name="HttpJsonpBinding" crossDomainScriptAccessEnabled="true"></binding>
      </webHttpBinding>
    </bindings>

    <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />

    <services>
      <service name="DebugSite.JSONP" behaviorConfiguration="EnableMetadataBehaviors">
        <endpoint address="" behaviorConfiguration="DebugSite.JSONPAspNetAjaxBehavior" binding="webHttpBinding" bindingConfiguration="HttpJsonpBinding" contract="DebugSite.JSONP" />
      </service>
    </services>
  </system.serviceModel>

在客户端使用Jquery调用的代码:

               var sendingInterval = document.getElementById("sendingInterval");
//            alert(sendingInterval.value);
              var displayUserName = document.getElementById("displayUserName");
//            //alert(displayUserName.innerHTML);

   var mydata = { UserName: displayUserName.innerHTML, Interval: sendingInterval.value};

    var url = "http://192.168.19.17/NewSpamReachedNotify/SettingSapmInterval.asmx/settingInterval?jsoncallback=?"

    $.getJSON(url, mydata,
         function (data) {
             if (data == "True") {
                 alert("设定成功");
             } else {
                 alert("设定失败");
             } });

如果没有参数则 ,则不填写,不需要使用null。  $.getJSON(url,function(data) {

           if (data == "True") {
                 alert("设定成功");
             } else {
                 alert("设定失败");
             } });

 

posted @ 2013-07-30 11:07  迷途的小榔头  阅读(160)  评论(0)    收藏  举报