【发布时间】:2019-05-11 23:51:36
【问题描述】:
Python用户,学习一些基本的javascript:
我创建了一个简单的烧瓶应用程序进行演示。 (为了快速测试,我在 Github 上放了这个例子:https://github.com/robertdavidwest/flask_d3_example)
dependencies:
- python=3.7.1
- flask=1.0.2
- flask-cors=3.0.7
和https://d3js.org/d3.v5.min.js
应用程序:
.
├── run.py
├── static
│ └── js
│ └── data.js
└── templates
└── index.html
我正在从一个烧瓶应用程序提供数据:
from flask import Flask, render_template, jsonify
from flask_cors import CORS
app = Flask(__name__)
CORS(app)
@app.route("/get-data")
def get_data():
return jsonify({"a": 1, "b": 2})
在服务器运行的情况下,如果我导航到http://127.0.0.1:5000/get-data,那么我会看到数据。
但是当我尝试使用d3.json 从前端请求数据时,似乎什么也没发生(我尝试记录数据并写入 div):
d3.json("http://127.0.0.1:5000/get-data",
function(d){
console.log(d);
document.getElementById("d3-write-here").innerHTML = d;
})
任何指导将不胜感激。
简单应用中所有代码的详细信息:
index.html:
<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset="utf-8" />
<title>Simple Example</title>
</head>
<body>
<h2>Nothing much here</h2>
<div id="d3-write-here"></div>
<script src="https://d3js.org/d3.v5.min.js"></script>
<script src="{{ url_for('static', filename='js/data.js') }}">
</script>
运行.py:
from flask import Flask, render_template, jsonify
from flask_cors import CORS
app = Flask(__name__)
CORS(app)
@app.route("/")
def index():
return render_template("index.html")
@app.route("/get-data")
def get_data():
return jsonify({"a": 1, "b": 2})
if __name__ == '__main__':
app.debug = True
app.run()
静态/js/data.js:
d3.json("http://127.0.0.1:5000/get-data",
function(d){
console.log(d);
document.getElementById("d3-write-here").innerHTML = d;
})
【问题讨论】:
-
d3v5 使用 fetch (Promises),doc d3-fetch,注意 CORS
标签: javascript python json d3.js flask