【问题标题】:Ionic/Angular js Parsing JSON data from serverIonic/Angular js 从服务器解析 JSON 数据
【发布时间】:2015-12-26 03:18:36
【问题描述】:

如何使用 Ionic/Angular js 从服务器解析 JSON 对象?从 /js 文件夹加载 json 时,这对我有用:

var rssApp = angular.module('myApp', []);
rssApp.controller('datas', ['$scope', '$http', function($scope,$http) {
$http.get("js/data.json") // <=== this
  .then(function (response) 
  {
   $scope.dat = response;
  });
}]);

但是当我从网络服务器加载 json 时,我得到了空白,这是我的代码:

var rssApp = angular.module('myApp', []);
rssApp.controller('datas', ['$scope', '$http', function($scope,$http) {
$http.get("http://localhost/data.json") //<== this 
  .then(function (response) 
  {
   $scope.dat = response;
  });
}]);

感谢您的帮助..

【问题讨论】:

  • 请您尝试在 plunker plnkr.co/edit/nJWuXYUHtOdHTML3Qi6l?p=preview 上写一个演示,这有助于我们更好地了解您的问题。你能看看你的javascript控制台,如果你有错误,让我们知道吗?最好的,
  • 你用'localhost/data.json'获取数据..???
  • 您遇到错误了吗?您是否尝试过使用 $resource 而不是 $http?如果你 console.log 你的回复,里面有什么吗?
  • 您应该使用浏览器导航到http://localhost/data.json 来获取数据。如果返回数据,它就是你的前端。如果没有,问题(可能)出在您的后端
  • @the_mahasagar 是的.. 我想从服务器获取数据;

标签: angularjs json ionic


【解决方案1】:

分析您到目前为止所做的事情,我想您的数据作为数组从网络服务器返回,因为您的代码变得空白。因此,您应该将 response[0] 分配给 $scope.dat

var rssApp = angular.module('myApp', []);
rssApp.controller('datas', ['$scope', '$http', function($scope,$http) {
$http.get("http://localhost/data.json") //<== this 
  .then(function (response) 
  {
   $scope.dat = response[0];
  });
}]);

【讨论】:

    【解决方案2】:

    首先

    Angular 的 $http 承诺响应 contains a few properties

    从服务器返回的数据将在data 属性中。

    来自 Angular 文档:

    响应对象具有以下属性:

    • data – {string|Object} – 用 `变换函数。
    • status – {number} – 响应的 HTTP 状态代码。
    • headers – {function([headerName])} – 标头获取函数。
    • config – {Object} – 用于生成请求的配置对象。 statusText – {string} – 响应的 HTTP 状态文本。

    您还想确保端点指向正确的资源。 即如果data.json 在您的应用程序文件中,那么路径将是path/to/data.json。这应该很容易识别,因为您会在响应对象中获得 404 状态代码。

    解决方案

    所以你可能想做这样的事情:

    var endpoint = "path/to/data.json";
    $http.get(endpoint).then(function (response) {
       $scope.dat = response.data;
    });
    

    还有一件事

    此外,如果有疑问,用户 console.debug(response); 将允许您检查响应对象。

    【讨论】:

      猜你喜欢
      • 2023-03-16
      • 1970-01-01
      • 2017-10-04
      • 1970-01-01
      • 1970-01-01
      • 2014-01-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多