【发布时间】:2013-09-02 23:47:08
【问题描述】:
我有一个使用 JSON 的 WCF REST 样式服务,它在 IE 中运行良好,但 FireFox 和 Chrome 正在发脾气;关于跨域调用。
我听从了这里的建议: Problem sending JSON data from JQuery to WCF REST method
但我现在看到的是,虽然我的浏览器发送了 2 个请求(首先是 OPTIONS,然后是 POST),但 POST 请求根本没有返回任何内容。再次,IE 与此完美配合。缺少什么?
JAVASCRIPT:
<script type="text/javascript">
function Search() {
var json = JSON.stringify($('#testForm').serializeObject());
$.ajax(
{
type: "POST",
url: "http://localhost:8000/MyService.svc/Search",
data: json,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response, status, xhr) {
GetResults(response.SearchResult.QueryId);
},
error: function (xhr, status, error) {
alert("Error\n-----\n" + xhr.status + '\n' + xhr.responseText);
},
//complete: function (jqXHR, status) { alert('Status: ' + status + '\njqXHR: ' + JSON.stringify(jqXHR)); }
});
return false;
}
function GetResults(queryId) {
debugger;
$.ajax(
{
type: "GET",
url: "http://localhost:8000/MyService.svc/GetResults?queryId=" + queryId + "&ignoreXmlFeedSourceIds=",
//data: {},
contentType: 'application/json; charset=utf-8',
dataType: "json",
success: function (response, status, xhr) {
debugger;
DoSomethingWithResults(response);
},
error: function (xhr, status, error) {
alert(error);
},
complete: function (jqXHR, status) { alert('Status: ' + status + '\njqXHR: ' + JSON.stringify(jqXHR)); }
});
}
function DoSomethingWithResults(results) {
alert("In DoSomethingWithResults()");
// process the results here to show on UI
debugger;
};
$.fn.serializeObject = function () {
var o = {};
var a = this.serializeArray();
$.each(a, function () {
if (o[this.name] !== undefined) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};
</script>
服务合同:
[ServiceContract]
public interface IMyService
{
[OperationContract]
[WebInvoke(BodyStyle = WebMessageBodyStyle.Wrapped, Method = "POST", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, UriTemplate = "/Search")]
SearchResponse Search(RequestInfo requestInfo);
[OperationContract]
[WebInvoke(Method = "OPTIONS", UriTemplate = "/Search")]
void SearchAllowCors();
[OperationContract]
[WebInvoke(BodyStyle = WebMessageBodyStyle.Wrapped, Method = "GET", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, UriTemplate = "/GetResults?queryId={queryId}&ignoreXmlFeedSourceIds={ignoreXmlFeedSourceIds}")]
IList<FlightJourneyAvailabilityResponse> GetResults(string queryId, string ignoreXmlFeedSourceIds);
}
【问题讨论】:
-
AJAX 参数中的额外逗号
-
Chrome 和 Firefox 对 CORS 有严格的限制。因此它们不允许通过 jquery 调用跨域服务。您可以使用 JSONP 通过 Jquery 实现跨域调用,但仅支持 GET 操作。
-
@Rajesh 这完全不正确。 CORS 在 Chrome 和 Firefox 中得到很好的支持。这些浏览器中的每一个都遵循规范,并且使用 jQuery 可以实现跨域 ajax 请求并且很简单。
-
@RayNicholus :对不起,我说他们不允许跨域请求,但我猜在 https 下他们会阻止它,因为这是我的经验,我不得不使用 JSONP。
标签: json wcf cross-domain