如何获取AJAX以使用从flask发送的JSON数据填充Datatables并单独呈现html?

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (1)
  • 关注 (0)
  • 查看 (966)

现在一切都成功了。如果要加载包含JSON有效负载的文件,请取消注释这一行

// "url": "static/objects2.txt", // This works for a static file

评论一下这个,

"url": "/index_get_data", // This now also works

flaskTest.py

from flask import Flask, render_template, jsonify

app = Flask(__name__)

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

@app.route('/index_get_data')
def stuff():
  # Assume data comes from somewhere else
  data = {
    "data": [
      {
        "id": "1",
        "name": "John Q Public",
        "position": "System Architect",
        "salary": "$320,800",
        "start_date": "2011/04/25",
        "office": "Edinburgh",
        "extn": "5421"
      },
      {
        "id": "2",
        "name": "Larry Bird",
        "position": "Accountant",
        "salary": "$170,750",
        "start_date": "2011/07/25",
        "office": "Tokyo",
        "extn": "8422"
      }]
  }
  return jsonify(data)


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

/模板/index.html

<!DOCTYPE html>
<html lang="en">
<head>
  <title>Datatables Example</title>
  <meta charset="utf-8">
  <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.18/css/jquery.dataTables.min.css"/>
  <script src="https://code.jquery.com/jquery-3.3.1.js"></script>
  <script src="https://cdn.datatables.net/1.10.18/js/jquery.dataTables.min.js"></script>
</head>
<body>
<h1>My Heading</h1>
<table id="example" class="display" style="width:100%">
        <thead>
            <tr>
                <th>Name</th>
                <th>Position</th>
                <th>Office</th>
                <th>Extn.</th>
                <th>Start date</th>
                <th>Salary</th>
            </tr>
        </thead>
        <tfoot>
            <tr>
                <th>Name</th>
                <th>Position</th>
                <th>Office</th>
                <th>Extn.</th>
                <th>Start date</th>
                <th>Salary</th>
            </tr>
        </tfoot>
    </table>
<script>


function setupData() {
    $(document).ready(function () {
        $('#example').DataTable({
            "ajax": {
                // "url": "static/objects2.txt", // This works for a static file
                "url": "/index_get_data", // This now also works
                "dataType": "json",
                "dataSrc": "data",
                "contentType":"application/json"
            },
            "columns": [
                {"data": "name"},
                {"data": "position"},
                {"data": "office"},
                {"data": "extn"},
                {"data": "start_date"},
                {"data": "salary"}
            ]
        });
    });
}

$( window ).on( "load", setupData );
</script>
</body>
</html>
提问于
用户回答回答于

不是做return render_template()

只要做:return jsonfiy(my data)

你正在发送数据,而不是视图,因此不需要将模板呈现作为响应返回。

扫码关注云+社区

领取腾讯云代金券