【发布时间】:2016-08-14 00:29:44
【问题描述】:
我收到一个有效的 JSON 请求,但只调用了 $http fail 方法。它在萤火虫中显示OK 200。视图也没有更新。新手尝试 AngularJS,所以有些东西可能太错误了:)
$http.jsonp("http://localhost:51377/api/Books/1").success(function(data, status, headers, config) {
alert("Suc");
$scope.people = data;
}).error(function(data, status, headers, config) {
$scope.people = data;
alert("fail");
});
这是 firebug 中的响应:
{"ID":1,"BookName":"ASP.Net"}
同样失败:
[{"ID":1,"BookName":"ASP.Net"}]
在$http 调用中的状态码中得到 404。我正在使用jsonp 应该注意CORS?当我从某个地方读到。我的角度在 file:// 协议中
更新 1: 尝试从 VS 在 localhost 中启动我的角度。相同的结果
更新 2:
我添加了配置更改以在我的后端 .net webapi 中删除 CORS,现在它可以与以下代码一起使用,但上面使用 jsonp 的原始代码仍然失败
$http({
method: 'get',
url: 'http://localhost:51377/api/Books/',
responseType: "json"
}).success(function (data, status, headers, config) {
alert(data);
console.log('Success: ' + data);
$scope.people = data;
}).error(function (data, status, headers, config) {
console.log('Error: ' + data);
});
【问题讨论】:
-
你试过把 Angular 文件放入 http 协议吗?
-
您是否尝试添加 ?callback=JSON_CALLBACK (请参阅下面的答案)?它在角度文档中。此外,这个 JSFiddle 表明它是必需的:jsfiddle.net/saarmstrong/hYACX/8/light
-
@MarkWatson 我会尝试并在这里更新。
标签: javascript .net angularjs json asp.net-web-api