[我正在尝试将烧瓶服务器中的JSON形式的列表传递到HTML中,以便可以使用p5.js进行显示,但无法传递数据
from flask import Flask, request, jsonify, render_template, url_for
import json
from random import randint
app = Flask(__name__)
COLUMNS = 8
ROWS = 8
NUMBER_OF_TILES = 7
def build_board():
#Setting all elements to 1 initially
board = [[1]*COLUMNS for i in range(ROWS)]
#Creating a random board with zero matches to begin
for r in range(ROWS):
for c in range(COLUMNS):
board[r][c] = randint(1, NUMBER_OF_TILES)
while (r>0 and board[r][c] == board[r - 1][c]) or (c > 0 and board[r][c] == board[r][c - 1]):
board[r][c] = randint(1, NUMBER_OF_TILES)
return board
@app.route('/', methods=["POST", "GET"])
def index():
if request.method == "POST":
data = json.dumps(build_board())
return render_template('index.html', data=data)
else:
return render_template('index.html')
if __name__ == "__main__":
app.run(debug = True)
所以这是烧瓶侧,然后html是:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="{{url_for('static', filename='js/p5.js')}}"></script>
<title>Document</title>
</head>
<body>
<form method="POST">
<input type='submit' value="Start Game" >
</form>
<script type='application/javascript'>
var json = {data}
var array = JSON.parse(json)
下面还有更多,但与问题无关
var json = {{ data|tojson }}