我设置了一个使用Windows身份验证的WCF RESTful服务,它运行良好。现在我想启用它进行跨域访问,所以我将js更改为以下内容:
$.ajax({
type: "GET",
url: "http://www.example.com/MyService.svc/GetData",
contentType: "application/javascript",
dataType: "jsonp",
async: false,
success: function (data) {
alert($.parseJSON(data));
},
error: function (ex) {
throw ex;
}
});
在Chrome开发人员工具中,在"网络"选项卡下,我可以看到请求有一个200状态代码,在"响应"选项卡中,我看到返回的数据。然而,在我的javascript中,成功块从未被调用。它进入带有错误的错误块:
Uncaught #<Object>
$.ajax.error
x.Callbacks.c
x.Callbacks.p.fireWith
k
x.ajaxTransport.send.n.onload.n.onreadystatechange
我错过了什么?
如果将contenttype更改为"application/json;charset=utf-8"并不能解决问题,那么您可以尝试以下代码:
如果您想启用它进行跨域访问,那么您应该在global.asax.cs文件中包含以下代码。
protected void Application_BeginRequest(object sender, EventArgs e)
{
EnableCrossDmainAjaxCall();
}
private void EnableCrossDmainAjaxCall()
{
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*");
if (HttpContext.Current.Request.HttpMethod == "OPTIONS")
{
HttpContext.Current.Response.AddHeader("Cache-Control", "no-cache");
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "POST");
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept");
HttpContext.Current.Response.AddHeader("Access-Control-Max-Age", "1728000");
HttpContext.Current.Response.End();
}
}
您可以编写如下代码的ajax调用函数:
$.ajax({
isPostBack: false,
type: "GET",
url: "http://www.example.com/MyService.svc/GetData",
async: false,
cache: false,
type: 'POST',
contentType: "application/json; charset=utf-8",
data: '{}',
dataType: 'json',
crossDomain: true,
success: function (data) {
alert($.parseJSON(data));
},
error: function (ex) {
throw ex;
}
});