【问题标题】:Unable to access Json using http.get . status is coming out is -1无法使用 http.get 访问 Json。出来的状态是-1
【发布时间】:2015-12-27 09:37:59
【问题描述】:

我是 AngularJS 的新手。在我的代码中,我尝试使用 $http.get 访问 json 数据,但它会出错并且状态返回为 -1 。

出了什么问题?

RecordApp.factory('recordaccess', ['$http', function($http) {
    $http.get('http://someurlforjson')
        .success(function(data) {
            return data;
        })
        .error(function(data, status, headers, config) {
            alert("Error occurred. Status: " + status);
        });
}]);

【问题讨论】:

  • 可能是跨域问题
  • 他在成功回调中返回数据..可能是这个问题
  • 使用 Angular 发出 get 请求非常简单。当您将发出 get 请求的 url 复制到浏览器中时会发生什么。您调用的网址有效吗?另外,什么是-1错误,我从来没有听说过
  • 谢谢保罗.. 是的,当我将 url 粘贴到浏览器中时它可以工作.. 即使我不确定这个状态 -1。
  • data 在您的error() 函数中记录为什么?

标签: javascript angularjs json http get


【解决方案1】:

$http 旧式 promise 方法 successerror 已被弃用。请改用标准的then 方法:

RecordApp.factory('recordaccess', ['$http', function($http) {
    return $http.get('http://someurlforjson')
        .then(function successCallback(response) {
            // this callback will be called asynchronously
            // when the response is available
            return response.data;
        },
        function errorCallback(response) {
            // called asynchronously if an error occurs
            // or server returns response with an error status.
            alert("Error occurred. Status: " + reponse.status + " - " + response.statusText);
        });
}]);

您可以在Angular Docs找到更多信息。

如果这没有帮助,那么您的 JSON 的路径一定有问题(路径不正确或者您无权访问它,例如 CORS)。

【讨论】:

  • 感谢 Mastertinner 对我的指导。我尝试了您的代码,但最终也得到了相同的状态代码 -1 。我怀疑同样的跨域问题,但不确定为什么我在 status 中得到 -1 。此外, response.statusText 即将空白。有人可以帮我处理跨域问题吗?
  • 这个return 会去哪里?如果没有将 $http 返回给变量或函数,您也无法访问回调的返回
  • @varunkumar,如果您像我在回答中所做的那样,在声明前添加 return 会怎样?
  • 我遇到了一次医疗紧急情况。现在我回来工作了。有人可以检查我的下面的代码,让我知道我在这里做错了什么。我使用本地 json 只是为了尝试新的then 方法: RecordApp.factory('recordaccess', ['$http', function($http) { return $http.get('record1.json') then(function successCallback(response) { return response.data; } , function errorCallback(response) {alert("发生错误。状态:" + response.status + " - " + response.statusText); }); }]);
  • @varunkumar,你需要有一个“。”在“then”之前: RecordApp.factory('recordaccess', ['$http', function($http) { return $http.get('record1.json').then(function successCallback(response) { return response. data; }, function errorCallback(response) {alert("发生错误。状态:" + response.status + " - " + response.statusText); }); }]);
猜你喜欢
  • 2017-10-25
  • 1970-01-01
  • 2022-01-09
  • 2011-04-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多