我今天大部分时间都在努力弄清楚为什么我的jQuery ajax调用我的独立HTML页面到跨域ASP.Net MVC Web API调用返回正确的JSON数据,但我得到了在我的ajax调用的错误部分中跟随错误消息:
对象{readyState = 4,状态= 404,statusText =“错误”,更多...}
我正在使用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中的网络流量选项卡。两种方式都显示对我的服务器的两个不同的调用:预检和实际请求。 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,它说它的格式正确。我不确定发生了什么。有什么见解吗?
答案 0 :(得分:1)
我也有这个问题并按如下方式解决:
'json'
更改为'jsonp'
WebApiContrib.Formatting.Jsonp
通过JsonpFormatter
:
Global.asax
来注册
configuration.Formatters.Insert(0, new JsonpMediaTypeFormatter(configuration.Formatters.JsonFormatter));
问题是Web API不知道如何说jsonp,这是唯一可以在跨域AJAX调用中使用的dataType。