我正在尝试从外部域调用 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/