我今天大部分时间都在试图弄清楚为什么我在独立 HTML 页面中对跨域 ASP.Net MVC Web API 调用的 jQuery ajax 调用返回了正确的 JSON 数据,但我收到以下错误消息在我的ajax调用错误部分:
对象 { readyState=4, status=404, statusText="error", 更多...}
我正在使用 jQuery 2.0.3。这是我的ajax调用代码:
$.ajax
({
type: "GET",
beforeSend: function (xhr, settings)
{
xhr.setRequestHeader("Authorization", "95d11869-a2ad-4925-8a16-ee23c82909ac");
},
url: url,
dataType: "json",
processData: false,
crossDomain: true,
success: function (jsonFromServer)
{
alert(JSON.stringify(jsonFromServer));
},
error: function (xhr, textStatus, errorThrown)
{
if (typeof console === 'object' && typeof console.log === 'function')
{
console.log(xhr);
console.log(textStatus);
console.log(errorThrown);
}
}
});
我可以通过两种不同的方式验证对我的 WEB API 服务的调用:通过 Fiddler 和通过 firebug 中的网络流量选项卡。两种方式都显示对我的服务器的 2 个不同调用:预检和实际请求。Fiddler 显示了实际的 JSON 数据结果,我已经针对 JSLint 进行了验证,并且 JSON 格式正确。我的服务的网络流量选项卡的第二个条目指示 200 状态,但响应为空。
这是我的请求标头:
GET /api/gamelist HTTP/1.1
Host: local.XXXXXX.com
User-Agent: Mozilla/5.0 (Windows NT 6.2; WOW64; rv:24.0) Gecko/20100101 Firefox/24.0
Accept: application/json, text/javascript, */*; q=0.01
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Authorization: 95d11869-a2ad-4925-8a16-ee23c82909ac
Referer: http://127.0.0.1:52148/index.html
Origin: http://127.0.0.1:52148
Connection: keep-alive
这是我的响应标题:
HTTP/1.1 200 OK
Cache-Control: no-cache, no-store
Pragma: no-cache
Content-Type: application/json; charset=utf-8
Expires: -1
Server: Microsoft-IIS/8.0
Access-Control-Allow-Origin: *
Access-Control-Allow-Origin: http://127.0.0.1:52148
X-AspNet-Version: 4.0.30319
Access-Control-Allow-Origin: *
Access-Control-Allow-Methods: POST, PUT, GET, DELETE, OPTIONS
Access-Control-Allow-Credentials: true
Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With
Access-Control-Max-Age: 86400
Date: Fri, 04 Oct 2013 20:22:43 GMT
Content-Length: 683
我已经阅读了很多帖子,并看到了人们认为有效的示例。我不确定我做错了什么。请问有人有什么见解吗?
更新
我打开了 Firefox 的 WebDeveloper Network 工具来监控请求的传输。我注意到它为我的服务器的跨域调用报告了以下内容:
语法错误:JSON.parse:数据意外结束。
这是我通过 fiddler 获得的服务调用返回的 JSON 数据:
{"Player":{"PersonId":33,"PersonName":"Anonymous User","UserKey":"95D11869-A2AD-4925-8A16-EE23C82909AC","EmailAddress":"unknown"},"GameList":[{"GameId":17,"QuestionTypeId":1,"QuestionTypeName":"Baseball","QuestionId":6,"QuestionName":"Basbeball Team Names","GameTypeId":2,"GameTypeName":"Solo","TotalAvailablePoints":141,"StartDate":"2013-10-04T11:17:10.277","WhosTurnIsItId":33,"WhosTurnName":"Anonymous User"},{"GameId":18,"QuestionTypeId":1,"QuestionTypeName":"Baseball","QuestionId":3,"QuestionName":"World Series Winners","GameTypeId":2,"GameTypeName":"Solo","TotalAvailablePoints":149,"StartDate":"2013-10-04T11:17:10.277","WhosTurnIsItId":33,"WhosTurnName":"Anonymous User"}]}
我在 JSLint 中粘贴了这个 JSON,它说它的格式正确。我不确定发生了什么事。有什么见解吗?