如何将非JSON可序列化的数据从flask传递到javascript文件?

2024-09-27 17:42:53 发布

您现在位置:Python中文网/ 问答频道 /正文

在我的服务器.py,我有一个记录姓名的列表:

data = [
"Jim",
"Stanley",
"Michael",
"Kevin",
"Kelly"
]

执行{data | tojson}}对我不起作用,因为这种格式的数据是不可序列化的。执行return render_template('ppc.html', data=data)似乎也不允许js文件访问数据服务器.py. 我也尝试过'{{data}}'这种格式在一些帖子中被推荐,但这些似乎都不起作用。有人有别的办法吗?你知道吗


Tags: 数据py服务器列表data序列化格式记录
1条回答
网友
1楼 · 发布于 2024-09-27 17:42:53

使用jsonify方法。它将允许从view返回listjsonify的文档。你知道吗

下面是一个如何使用Javascript在模板中加载数据的示例。你知道吗

文件夹结构:

├── app.py
├── static
│   └── demo.js
└── templates
    └── simple.html

app.py

from flask import Flask, render_template, jsonify

app = Flask(__name__)

@app.route("/get_data", methods=['GET'])
def get_data():
    data = ["Captain America", "Hulk", "Thor", "Wolverine"]
    return jsonify(data)

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

app.run(debug=True)

simple.html

<html>
    <head>
        <title>Marvel Characters</title>
    </head>
    <body>
        <h3>List of Marvel Characters loaded from JS</h3>
        <div id="result"></div>
        <script src="{{ url_for('static', filename='demo.js') }}"></script>    
    </body>
</html>

demo.js

window.addEventListener("load", function(){
    var xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
            var data = JSON.parse(this.responseText);
            var result = document.getElementById("result");
            for(var i=0;i<data.length; i++){
                result.innerHTML += data[i]+"<br>";
            }           
        }
    };
    xhttp.open("GET", "/get_data", true);
    xhttp.send();
});

输出:

output of data loading from JS

相关问题 更多 >

    热门问题