无法获取web api json响应的内容,返回空白

时间:2016-06-28 18:30:58

标签: javascript html angularjs json

我是前端编程的初学者;但是,我在后端c#(非网络资料)中经验丰富。

我有2个视觉工作室开放。一个是提供web api,另一个是使用web api。

如何从远程源读取和显示json?

尝试阅读其中一个API时,该页面什么也没有显示。

我的HTML:

<!doctype html>
<html ng-app="myApp">
<head>
    <title>Hello AngularJS</title>

    <script src="Scripts/angular.js"></script>
    <script src="app.js"></script>
    <script src="controllers/GbyG.js"></script>
</head>

<body ng-controller="GbyG">

<table border="1">
    <tr ng-repeat="data in greeting">
        <td>{{data.FirstName}}</td>
    </tr>
</table>


</body>
</html>

GbyG.js

'use strict';

app.controller('GbyG',
        function($scope, $http) {
            $http.get('http://localhost:36059/api/Samples/GetAllSamplesByStatusUser')
                .success(function(data) {
                    $scope.greeting = data;

                });
        }

);

app.js

'use strict';
var app = angular.module('myApp', []);

我正在阅读的json样本

[{"Sample":{"sampleid":1,"barcode":"129076","createdat":"2015-01-02T00:00:00","createdby":6,"statusid":3},"Status":"Report Generation","FirstName":"Clint","LastName":"Reid"},{"Sample":{"sampleid":2,"barcode":"850314","createdat":"2015-06-15T00:00:00","createdby":7,"statusid":3},"Status":"Report Generation","FirstName":"Kim","LastName":"Mullins"}]

如何从远程源读取和显示json?

2 个答案:

答案 0 :(得分:2)

  

参考$http docs

  • 使用.then处理程序而不是.success,因为以后会被删除
  • 访问响应对象的data属性,因为它包含data

'use strict';
var app = angular.module('myApp', []);
app.controller('GbyG',
  function($scope, $http) {
    $http.get('http://thetraveltemple.com/webservices/fetchCountry.php')
      .then(function(data) {
        $scope.greeting = data.data;
      });
  }
);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<body ng-app="myApp" ng-controller="GbyG">
  <table border="1">
    <tr ng-repeat="data in greeting.countries">
      <td>{{data.country_name}}</td>
    </tr>
  </table>
</body>

答案 1 :(得分:1)

这是plnkr http://plnkr.co/edit/1MkV3qJ7WupKkNlybZNT?p=preview

你可以在get调用中替换rest服务而不是tag.json,我用它来测试。

您的JSON应该采用这种格式。

[{
  "Status": "Report Generation",
  "FirstName": "Clint",
  "LastName": "Reid",
  "Sample": {
    "sampleid": 1,
    "barcode": "129076",
    "createdat": "2015-01-02T00:00:00",
    "createdby": 6,
    "statusid": 3
  }
}, {
  "Status": "Report Generation",
  "FirstName": "Kim",
  "LastName": "Mullins",
  "Sample": {
    "sampleid": 2,
    "barcode": "850314",
    "createdat": "2015-06-15T00:00:00",
    "createdby": 7,
    "statusid": 3
  }

}]