2015-08-03 150 views
1

当我使用这个URL(http://localhost:8080/jerseyweb/crunchify/ftocservice)时,我制作了一个Web服务,它返回一个JSON格式的数据。现在我想通过Angular js获取这些数据,但我无法得到它。该代码与我尝试,情况如下:Angularjs和Web服务

<!DOCTYPE html> 
<html> 
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script> 
<body> 
<div ng-app="myApp" ng-controller="customersCtrl"> 

<ul> 
<li ng-repeat="x in names"> 
{{ x.id + ', ' + x.name }} 
</li> 
</ul> 
</div> 

<script> 
var app = angular.module('myApp', []); 
    app.controller('customersCtrl', function($scope, $http) { 
    alert("hi"); 
    $http.get("http://localhost:8080/jerseyweb/crunchify/ftocservice") 
    .success(function (data, status, headers, config) { 
alert("hiee"); // i can not reach at this alert 
    $scope.names = data; 


}); 
}); 
</script> 

</body> 
</html> 

http://localhost:8080/jerseyweb/crunchify/ftocservice的JSON数据如下

[{"id":98.24,"name":36.8}] 
+0

你有没有在控制台中的任何错误?另外我认为成功函数只有一个参数(数据)。尝试删除所有其他参数 – Kram

+0

我尝试,但我不能得到任何东西出来........ –

+0

也不会得到任何错误,但我尝试调试,发现调试调用不能进入此:$ http.get(“http:// localhost:8080/jerseyweb/crunchify/ftocservice”) .success(function(data,status,headers,config)alert(“hiee”); //我不能达到此警报 $ scope.names = data; }); –

回答

1

有一个在Web服务响应的错误.....

@OPTIONS 
@Path("/getsample") 
public Response getOptions() { 
return Response.ok() 
    .header("Access-Control-Allow-Origin", "*") 
    .header("Access-Control-Allow-Methods", "POST, GET, PUT, UPDATE, OPTIONS") 
    .header("Access-Control-Allow-Headers", "Content-Type, Accept, X-Requested-With") 
.build(); 

}

0

请试试这个代码可能是它使用全:

var response = $http({ 
       method: "GET", 
       url: "http://localhost:8080/jerseyweb/crunchify/ftocservice", 
       dataType: "json" 
      }); 



response.then(function (obj) { 
      $scope.names = obj.data.name; 
     }, function() { 
      alert('Error.'); 
     });   

如果数据来自字符串格式的API,则使用

var objdata = JSON.parse(obj.data); 
$scope.names = objdata.name; 
+0

如果API也是相同的位置,则使用 url:“/ jerseyweb/crunchify/ftocservice” , –

+0

我试试这个,它出错了...... –

+0

你能告诉我究竟有什么错误吗? –