AngularJS $ http.get()总是返回错误?

问题描述:

为什么下面的代码在没有状态的情况下运行错误回调? Firefox中的Web开发人员报告状态码为200.

有什么方法可以调试吗?

<meta charset="utf8"> 

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.1.5/angular.min.js"></script> 

<script type="text/javascript"> 

    function RoomListCtrl($scope, $http) { 

     $scope.getRooms = function() { 

       $http({method: 'GET', url: 'http://code.angularjs.org'}). 

       success(function(data, status, headers, config) { 
       // this callback will be called asynchronously 
       // when the response is available 
        alert('succes'); 
       }). 

       error(function(data, status, headers, config) { 
       // called asynchronously if an error occurs 
       // or server returns response with an error status. 
        alert('error'); 
       }); 
     } 

     $scope.submit = function() { 

      this.getRooms(); 
     } 

    } 

</script> 

<body ng-controller="RoomListCtrl"><form ng-submit="submit()"> 
    <input type="text" value="" ng-model="search" name="search" > 
</form></body> 

+0

是你正在运行的实际代码?听起来像是你遇到[跨域](http://en.wikipedia.org/wiki/Same-origin_policy)问题,实际的请求被阻止(所以没有状态)。 – robertklep

+0

是的,这是实际的代码。我在Firefox中将此代码作为本地文件运行。这可能导致问题吗? – koen

+0

即使通过HTTP服务器运行它,也会产生错误,因为通常不能执行跨域AJAX请求(除非处理请求的远程服务器具有[CORS](http:// enable-cors)。 org /)启用,但它看起来不像'code.angularjs.org')。 – robertklep

正如上面@robertklep指出,你不能让Ajax请求到另一个域,除非该域明确允许。请参阅他提供的CORS链接。对此的一种解决方法(假设您无法控制您请求数据的服务器的CORS策略)是在服务器支持该请求时使用JSONP请求。