我有一个问题,根据使用 jQuery 从 aspx 页面调用 json wcf 方法。
这是我的测试方法:
[ServiceContract]
public interface IEParcelService
{
[OperationContract]
[WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Wrapped,
UriTemplate = "Test")]
Response<string> Test();
}
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class EParcelServiceImpl : IEParcelService
{
public Response<string> Test()
{
return WebServiceHelper.Execute(() => "Test Message");
}
}
此服务部署到 IIS。 当我从 Chrome 调用此方法时:http://localhost/TestService/ServiceImpl.svc/Test 一切都很好,我可以看到结果。但是当我从 jQuery 调用它时 我有错误:NETWORK_ERR: XMLHttpRequest Exception 101。我尝试在 Google 中找到解决方案。 但结果并没有成功。我该如何解决?
jQuery 调用:
<script language="javascript">
$().ready(function () {
$("#myButt").click(function () {
$.ajax({
cache: false,
async: false,
type: "GET",
url: "http://localhost/EParselService/EParcelServiceImpl.svc/Test",
contentType: "application/json",
dataType: "json",
success: function (data, textStatus){
alert('successCallBack called');
alert(data);
alert(textStatus);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert('errorCallBack called');
alert('textStatus = ' + textStatus + '/nerrorThrown = ' + errorThrown);
}
});
alert('Done!');
});
});
</script>
<input type="button" value="Get values from server" id="myButt" />
最佳答案
所以这是一个同源问题。 (参见here)
对于 XMLHttpRequest,资源必须与请求它的页面位于完全相同的域中。这是为了防止 XSS(请参阅 here )攻击。如果你想使用来自不同域的资源,你必须使用 jsonp 之类的东西。 (请参阅 here )有关如何使用 WCF 执行此操作的良好教程。
关于jquery - 通过jQuery调用JSON wcf服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7280774/