我有一个返回 JSON 格式数据的 WCF 服务。当我使用 Web 浏览器时,我可以很容易地看到结果,但是当使用 Jquery getJSON 时,我无法让它工作。我可以在 fiddler 中看到它正在返回数据,但在 firebug 中它显示为红色字体和空响应。
这是我的 WCF 服务
[OperationContract]
[WebInvoke(Method = "GET",
ResponseFormat = WebMessageFormat.Json,
BodyStyle = WebMessageBodyStyle.Wrapped,
UriTemplate = "GetUrl/{iType}")]
String GetUrl(string iType);
public String GetUrl(string iType)
{
return strurl;
}
我的 JSON 调用看起来像这样
$.getJSON("http://localhost/UrlSvc/UrlService.svc/GetUrl/1",
function (data) {
console.log("Data JSOn Got");
$.each(data.items, function (i, item) {
console.log("Data Received");
});
});
当我把那个 url 放在浏览器中时,我得到了下面的响应,正如预期的那样
{"GetChartUrlResult":"ulr_fdba9bc2-7ff7-467f-a6e0-6f4d234169d2.png"}
但是 getJSOn 返回空响应,如在 Firebug 中看到的那样,url 本身上有红色字体。 这是一个跨域调用,我已经启用了它的跨域 WCF
请您参考如下方法:
浏览器不允许跨域 AJAX 调用并阻止 XMLHTTPRequest 发生在除加载包含脚本或页面的域之外的任何域。
要解决此问题,您可以使用将 AJAX 响应包装在 javascript 中的 JSONP 调用。您将以下查询字符串条目添加到您的请求中:
callback=?
另请注意,如果您使用的是 WCF,则需要在您的服务中启用 JSONP。您可以通过在您的配置文件中将 crossDomainScriptAccessEnabled 属性设置为 true 来执行此操作:
<system.serviceModel>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true"/>
<standardEndpoints>
<webScriptEndpoint>
<standardEndpoint name="" crossDomainScriptAccessEnabled="true"/>
</webScriptEndpoint>
</standardEndpoints>
</system.serviceModel>
可以找到有关 JSONP 和 WCF 的更多信息 here .
