从Flask发送json以响应Angularjs $ http.get

时间:2015-08-02 04:25:31

标签: json angularjs flask

我是网络编程的新手。我正在使用flask和angularjs,我正在尝试发送json数据以响应angularjs $ http.get请求。 angularjs代码来自本教程:https://www.youtube.com/watch?v=TRrL5j3MIvo。 我的文件夹结构如下:

routes.py
countries.json
/templates
   index.html

我得到的错误是在'index.html'的ng-repeat中,“country”没有定义。这告诉我'国家'没有获得json数据。但是,路线'/countries.json'有效。如果在终端中使用'python3 routes.py'运行服务器后在浏览器中输入http://localhost:5000/countries.json,它将显示json,这样很好,但来自angularjs的$ http.get没有读取它。运行http://localhost:5000时,当我在@ app.route('/ countries.json')中输入一个时,它甚至不会打印出一个print语句,这告诉我我误解了$ http.get,也许它甚至没有到达'/countries.json'路线。有人可以告诉我这里缺少什么吗?谢谢!我确定我的问题是,除了返回json文件本身之外,还需要以某种方式从flask发送数据。但是我怎么发送呢?

这是我的routes.py

from flask import Flask, send_from_directory, render_template
import os
app = Flask(__name__)


@app.route('/')
def home():
    return render_template('Example20.html')

@app.route('/countries.json')
def jsonFile():
    return send_from_directory(os.path.abspath(os.path.dirname('countries.json')), 'countries.json')


if __name__ == '__main__':
    app.run(debug=True)

这是我的index.html

<html ng-app='countryApp'>
<head>
  <meta charset="utf-8">
  <title>Cool</title>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
  <script>
  var countryApp = angular.module('countryApp', []);
  countryApp.controller('CountryCtrl', function ($scope, $http){
    $http.get('countries.json').success(function(data) {
      $scope.countries = data;
    });
  });
  </script>
</head>
<body ng-controller='CountryCtrl'>
  <table>
    <tr>
      <th>Country</th>
      <th>Population</th>
    </tr>
    <tr ng-repeat='country in countries'>
      <td>{{country.name}}</td>
      <td>{{country.population}}</td>
    </tr>
  </table>
</body>
</html>

这是我的countries.json

[
  {
    "name": "WORLD",
    "population": 6916183000
  },
  {
    "name": "More developed regions",
    "population": 1240935000
  },
  {
    "name": "Less developed regions",
    "population": 5675249000
  }
]

1 个答案:

答案 0 :(得分:4)

来自documentation here的Angular&#39; $http.get()的响应是一个响应对象,其中包含一个名为data的属性。

因此,根据您当前的代码,您需要设置$scope.countries = data.data;

要调试响应,您可以添加console.log(data);并在您选择的浏览器中检查开发人员工具的控制台输出。

此外,如果我的修复程序出错了,您可以检查开发人员工具中的网络并查看实际返回的响应。学习使用浏览器开发人员工具,立即成为强大的开发人员!