gpt4 book ai didi

json - 获取 AJAX 使用从 Flask 发送的 JSON 数据填充数据表并单独渲染 html

转载 作者:行者123 更新时间:2023-12-01 23:13:21 24 4
gpt4 key购买 nike

现在一切正常了。如果要加载包含 JSON 负载的文件,请取消注释此行

//"url": "static/objects2.txt",//这适用于静态文件

并评论这个,

"url": "/index_get_data",//现在也可以了

flask 测试.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>

最佳答案

不要执行return render_template(),只需执行以下操作:

返回jsonfiy(我的数据)

您发送的是数据而不是 View ,因此无需返回模板渲染作为响应。

关于json - 获取 AJAX 使用从 Flask 发送的 JSON 数据填充数据表并单独渲染 html,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50919478/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com