2015-08-03 80 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

你能告訴我究竟有什麼錯誤嗎? –