【问题标题】:Parsing JSON file with angular.js使用 angular.js 解析 JSON 文件
【发布时间】:2015-06-02 19:57:13
【问题描述】:

我想用 angular.js 从 json 文件中解析比特币价格。

json来源为this blockchain api.

我用于 angular.js 的代码:

<div ng-app="myApp" ng-controller="customersCtrl"> 
  <ul>
    <li ng-repeat="x in price">
      {{ x.15m + ', ' + x.last }}
    </li>
  </ul>
</div>

<script>
  var app = angular.module('myApp', []);
  app.controller('customersCtrl', function($scope, $http) {
    $http.get("https://blockchain.info/de/ticker")
         .success(function (response) {$scope.price = response.USD;});
  });
</script>

结果应该是15m的价格,然后用逗号隔开最新的价格。

我的猜测是我在 response.USD 附近搞砸了一些东西,但是 1 小时后,我仍然没有找到正确的方法。

请帮忙!

【问题讨论】:

  • 应该是跨域请求所致。您是否在控制台、chrome 或 fiddler 的网络选项卡中看到错误?
  • @ShankarSangoli chrome 控制台抛出以下内容: 错误:[$parse:syntax] errors.angularjs.org/1.3.14/$parse/……5m%20%2B%20'%2C%20' %20%2B%20x.last&p4=.15m%20%2B%20'%2C%20'%20%2B%20x.last at Error (native) at ajax.googleapis.com/ajax/libs/angularjs/1.3.14/… at ib.throwError (ajax.googleapis.com/ajax/libs/angularjs/1.3.14/…) at ib.parse (ajax.googleapis.com/ajax/libs/angularjs/1.3.14/…) ....
  • {{ x.15m + ', ' + x.last }} 更改为 `{{ x["15m"] + ', ' + x.last }} 以消除此错误。但是通过这个错误之后,你仍然会遇到跨域请求的问题。
  • “跨域请求问题”虽然修复起来并不可怕。您可以发起对数据的服务器端请求。将其存储在本地文件中,当该请求返回时(在您的回调函数中),您可以在文件所在位置向您自己的服务器发送另一个请求。
  • 另外...如果有帮助,请您接受我的回答吗?

标签: json angularjs http


【解决方案1】:

看来您实际上是从区块链站点收到错误消息。他们在服务器上设置了单源策略,以保护他们免受点击劫持攻击。这是您遇到的错误:

XMLHttpRequest cannot load https://blockchain.info/de/ticker. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin '<your domain>' is therefore not allowed access.

您的选择是联系该站点并要求他们将您的服务器添加为例外,或者使用来自您服务器的某种 curl 请求,然后让您的 GET 请求访问您的本地副本。

创建一个名为results.php的文件,输入以下代码:

<?php

try {
    $curl = curl_init();
    curl_setopt_array($curl, array(
        CURLOPT_RETURNTRANSFER => 1,
        CURLOPT_URL => 'https://blockchain.info/de/ticker'
    ));

    $result = curl_exec($curl);

    echo $result;
} catch (Exception $e) {
    header("HTTP/1.0 500 Unable to pull ticker results");
    echo $e->getMessage();
}
?>

现在在您的脚本中将其更改为:

<script>
  var app = angular.module('myApp', []);
  app.controller('customersCtrl', function($scope, $http) {
    $http.get("results.php")
         .success(function (response) {$scope.price = response.USD;});
  });
</script>

另外,最后一件事。您的 ng-repeat 将一遍又一遍地重复相同的事情(如果您可以让它以这种方式工作),因为您正在为“x”中的每个值编写相同的内容。也许考虑将其更改为:

<div ng-app="myApp" ng-controller="customersCtrl">
    <p>{{price['15m']}}, {{price['last']}}</p>
</div>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-22
    • 2020-05-07
    • 2013-04-28
    • 2016-10-02
    • 2023-04-02
    相关资源
    最近更新 更多