如何使用AngularJS从外部URL获取JSON并在页面中显示 - 资源解释为脚本但使用MIME类型text / html传输

问题描述 投票:3回答:2

我正在尝试对URL进行http调用以获取JSON并在我的页面上显示它。

JSON看起来像这样:

{"ticker":{"high":484.01099,"low":470.37201,"avg":477.1915,"vol":2193393.03322,"vol_cur":4588.62668,"last":482.16,"buy":482.16,"sell":481.2,"updated":1398350394,"server_time":1398350394}}

代码包含在下面。我读到我必须使用'JSONP',但我无法弄清楚如何使用它。

<html ng-app>
    <body>
        <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.0-beta.6/angular.min.js"></script>
        <div id = "content" style="min-width: 1200px; max-width: 90%: margin-left: auto; margin-right: auto;">
            <div style="width: 520px; float: left;">
                <h4>Bot Summary:</h4>
            </div>
            <div  ng-controller="TickerControl" style="width: 680px; float: left;">
                <h4>Market Summary</h4>
                <p>Price = {{data}} </p>
            </div>
        </div>
        <div></div>

        <script type="text/javascript">

            function TickerControl($scope, $http, $templateCache) {
                $scope.method = 'JSONP';
                $scope.url = 'https://btc-e.com/api/2/btc_usd/ticker?callback=JSON_CALLBACK';

                $scope.getTicker = function() {
                  $scope.code = null;
                  $scope.response = null;

                  $http({method: $scope.method, url: $scope.url, cache: $templateCache}).
                    success(function(data, status) {
                      $scope.status = status;
                      $scope.data = data;
                    }).
                    error(function(data, status) {
                      $scope.data = data || "Request failed";
                      $scope.status = status;
                  });
                };

                            $scope.getTicker();
            }

        </script>

    </body>
</html>

UPDATE

我现在修改了我的代码以尝试执行JSONP请求。我收到以下错误:

Resource interpreted as Script but transferred with MIME type text/html: "https://btc-e.com/api/2/btc_usd/ticker?callback=angular.callbacks._0". angular.js:8582
Uncaught SyntaxError: Unexpected token : ticker:1

我似乎回来了。由于我无法控制服务器响应,我如何将此文本解析为JSON ...或者甚至只显示它...它可以在chrome dev环境中查看。

更新2

显然这似乎是服务器配置不正确的问题。由于我无法访问它,能够只接收文本并在客户端解析它会很好!

html json angularjs url jsonp
2个回答
3
投票

在做了一些更多的研究和尝试不同的方法之后,我很遗憾地告诉你,你想要实现的目标是无法完成的。

我向https://btc-e.com/api/2/btc_usd/ticker?callback=JSON_CALLBACK发送了一个GET请求以进行测试,并在响应标题中说明了这一点

content-type→text / html;字符集= utf-8的

因为您进行跨域调用而您无法访问服务器,所以必须使用jsonp。但jsonp不适用于text/html内容。这与错误有关

资源解释为脚本,但使用MIME类型text / html进行传输

因此,即使响应看起来像有效的JSON,客户端应用程序也不会将其视为有效。

要解决此问题,您必须在服务器上添加正确的Content-Type标头,但您无权访问它。

来自this related question的报价:

jsonp只能在服务器在javascript函数调用中正确嵌入响应时使用。


把它们加起来:

你也应该

  • 通过配置服务器来允许跨域调用
  • 通过配置服务器来发回适当的内容类型标头

可悲的是,你无法访问服务器。

请注意,这不是你的错。这是因为服务器配置不正确。


0
投票

如果响应包含纯文本,您可以使用“angular.fromJson(data)”解析它。使用GET请求获取数据(并确保响应实际上不包含HTML代码)。

© www.soinside.com 2019 - 2024. All rights reserved.