现在一切正常。如果要加载包含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)
/templates/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>
答案 0 :(得分:2)
要做的不是代替return render_template()
:
return jsonfiy(my data)
您发送的数据不是视图,因此无需返回模板渲染作为响应。