【发布时间】:2011-09-02 08:10:50
【问题描述】:
我对使用 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" />
【问题讨论】:
-
可能是跨站问题。您是否在同一个 iis 上托管您的 html?看看这里:jasonkelly.net/2009/05/….
-
我在 IIS 上托管服务,但我的测试网站在 Visual Studio 开发服务器上运行。
-
好了,您应该将它们都托管在同一个站点上。如果您想使用 XMLHttpRequest,因为它不允许在其范围之外打开追索权。这是为了防止 XSS 攻击。如果您想使用来自不同站点的资源,则必须使用 jsonp 之类的东西(参见我之前发布的内容)。
-
是的,你是对的。感谢您的帮助。