javascript - 从外部域调用 WCF 服务

标签 javascript jquery ajax wcf

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

Error: MyCallback was not called

示例应用程序:

<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);
}

最佳答案

该问题与不正确的网络服务 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> 

关于javascript - 从外部域调用 WCF 服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41873850/

相关文章:

jquery - iOS Safari 滚动到顶部在某些页面上不起作用。为什么?

javascript - 使用 Javascript 更新选项后刷新 HTML 选择

javascript - 格式化 momentjs 日期时间

javascript - 如何在 PHP 中访问嵌套数组的变量

javascript - 引用未声明的命名空间前缀 : 'soap' when parsing MSXML soap response using selectSingleNode

javascript - 使用 Javascript 通过链接抓取并发送文本值

jquery 模式打开整页

jquery - 如何很好地构建具有重复元素的表单

javascript - 谁用 Jquery Ajax 附加 php onchange

php - 使用 Ajax 检查按钮是否被点击