【问题标题】:angularJS $http.get communicating with APIangularJS $http.get 与 API 通信
【发布时间】:2015-05-22 03:36:05
【问题描述】:

我是 AngularJS 的新手,我正在尝试通过研究示例代码来理解它。

这里我有一个关于 $http.get 的内容,来自以下链接:

http://www.w3schools.com/angular/tryit.asp?filename=try_ng_customers_json

我刚刚用我自己的一个替换了 url 但它不起作用,我真的很困惑,请帮助,谢谢!

===========================

第二次编辑:感谢答案,双 ng-app 是一个错误,但这不是这个问题的主要原因。我认为这与跨站点阻止有关,但我已在我的 API 上将其关闭(我使用 codeigniter REST API 并设置了 $config['csrf_protection'] = FALSE; ),我不知道如何配置它。

<!DOCTYPE html>
<html>
    <head>
        <script src= "http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
    </head>
    <body ng-app="myApp">
        <div ng-controller="customersCtrl">
            <ul>
                {{names}}
            </ul>
        </div>
        <div ng-controller="myCtrl">
            <ul>
                {{names}}
            </ul>
        </div>
        <script>
        var app = angular.module('myApp', []);
        app.controller('customersCtrl', function($scope, $http) {
        $http.get("http://www.w3schools.com/website/Customers_JSON.php")
        .success(function (response) {$scope.names = response;});
        });
        app.controller('myCtrl', function($scope, $http) {
        $http.get("https://manage.pineconetassel.com/index.php/api/v1/colors2.php")
        .success(function (response) {$scope.names = response;});
        });
        </script>
    </body>
</html>

【问题讨论】:

  • 提及文件扩展名,如:.php 或 .html 并尝试
  • 第一个 ng-app 代码应该可以工作,其他将被忽略,将 ng-app 放在 html 元素中会很好

标签: javascript angularjs api


【解决方案1】:

问题是你有两个"myApp" 声明。 来自 AngularJS documentation:

每个 HTML 文档只能自动引导一个 AngularJS 应用程序。在文档中找到的第一个 ngApp 将用于定义根元素以自动引导为应用程序。

因此,您应该将ng-app="myApp" 移动到正文元素。 但是,一旦您完成此操作,您可能仍然看不到任何结果,因为您是跨站点脚本,并且浏览器将(默认情况下)阻止第二个请求。

【讨论】:

  • 我想让第二个工作,即使我删除了第一个,它仍然无法工作。我认为它与跨站点有关,但我不知道如何允许来自站点的 API,为什么当我一次尝试一个时,第一个有效而第二个无效?
  • This answner 很好地概述了当您控制服务器时可以做什么。如果不这样做,请尝试jsonp 而不是get$http.jsonp("https://manage.pineconetassel.com/index.php/api/v1/colors2.php?callback=JSON_CALLBACK")。还要注意回调。
【解决方案2】:

单个页面上的两个ng-app 指令将执行第一个,第二个将被忽略。

从您的 html 的两个 div 中删除 ng-app="myApp" 并使用 angular.bootstrap 使用以下代码在 html 页面上引导 Angular 应用程序。

代码

angular.element(document).ready(function() {
  angular.bootstrap(document, ['myApp']);
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-28
    • 1970-01-01
    • 2015-05-30
    • 1970-01-01
    • 1970-01-01
    • 2019-12-02
    相关资源
    最近更新 更多