从外部域调用WCF服务

时间:2017-01-26 12:50:50

标签: javascript jquery ajax wcf

我正在尝试从外部域调用WCF服务。似乎我在Fiddler中得到了正确答案,但$ ajax调用返回错误:

  

错误:未调用MyCallback

示例应用程序:

<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
    <script type="text/javascript">
    $(document).ready(function(){
        $("#button1").click(function(){
            $.ajax({
                url: "http://localhost:31492/LocationService.svc/GetLocation",
                data: '{"id":"33"}',
                dataType: "jsonp",
                type: "GET",
                timeout: 10000,
                jsonpCallback: "MyCallback",
                success: function (data, textStatus, jqXHR) {
                    $("#display").html(data);
                },
                error: function (jqXHR, textStatus, errorThrown) {    
                    alert(errorThrown);
                },
                complete: function (jqXHR, textStatus) {
                }
            });
            function MyCallback(data) {
            alert(data);
        }
        });
    });
    </script>
</head>

<body>
    <h1>Test</h1>
    <br><br><br>
    <div id="display">
    </div><br>
    <button id="button1">Get External Content</button>
</body>

编辑:WCF服务合同:

[ServiceContract(SessionMode = SessionMode.NotAllowed)]
public interface ILocationService
{
    [OperationContract]
    [WebGet(ResponseFormat = WebMessageFormat.Json)]
    string GetLocation(int id);
}

1 个答案:

答案 0 :(得分:0)

该问题与Web服务web.config错误有关:

<bindings>
  <webHttpBinding>
    <binding name="webHttpBindingWithJsonP" crossDomainScriptAccessEnabled="true" />
  </webHttpBinding>
</bindings>

<services>
  <service name="Services.LocationService" behaviorConfiguration="serviceBehavior">
    <endpoint address="" binding="webHttpBinding"
              bindingConfiguration="webHttpBindingWithJsonP"
              contract="Services.IkLocationService" behaviorConfiguration="webBehavior" />
  </service>
</services>