Javascript 无法使用http.get访问Json。状态显示为-1

Javascript 无法使用http.get访问Json。状态显示为-1,javascript,angularjs,json,http,get,Javascript,Angularjs,Json,Http,Get,我对AngularJS是新手。在我的代码中,我试图使用$http.get访问json数据,但它将出错,状态返回为-1 出什么事了 RecordApp.factory('recordaccess', ['$http', function($http) { $http.get('http://someurlforjson') .success(function(data) { return data; }) .error

我对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);
        });
}]);

$http legacy promise方法
success
error
已被弃用。改用标准
然后
方法:

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);
        });
}]);
您可以在中找到更多信息


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

在成功回调中返回数据时可能会出现跨源问题。。可能这就是问题所在使用angular发出get请求非常简单。在浏览器中复制要向其发出
get
请求的url时会发生什么情况。您调用的url有效吗?还有,什么是-1错误,我从未听说过。谢谢你,保罗。。是的,当我在浏览器中粘贴url时,它会工作。。即使我也不确定此状态-1.您的
error()
函数日志中的
数据是什么?感谢Mastertinner在这方面的指导。我尝试了你的代码,但也得到了相同的状态代码-1。我怀疑同样的跨域问题,但不确定为什么我的状态是-1。此外,response.statusText为空。有人能帮我处理跨域问题吗?这个
将返回到哪里?如果未将
$http
返回到变量或函数,则无法访问回调函数的返回either@varunkumar,如果您像我刚才在回答中所做的那样,在语句前面添加一个
return
,会怎么样?我遇到了一个医疗紧急情况。现在我回来工作了。请有人检查我下面的代码,让我知道我在这里做错了什么。我使用本地json只是为了尝试新的方法:RecordApp.factory('recordaccess',['http',函数($http){return$http.get('record1.json')然后(函数successCallback(response){return response.data;},函数errorCallback(response){alert(“Error occurrent.Status:”-“+response.statusText);});}]);@varunkumar在“then”:RecordApp.factory之前需要有一个“.”('recordaccess',['$http',函数($http){return$http.get('record1.json')。然后(函数successCallback(response){return response.data;},函数errorCallback(response){alert(“Error occurrent.Status:”+response.Status+“-”+response.statusText);});});