【问题标题】:request data from front end (d3.json) from python flask backend [duplicate]从python烧瓶后端请求来自前端(d3.json)的数据[重复]
【发布时间】: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


【解决方案1】:

在 d3 v5 中,您需要对 json 调用使用不同的语法。

试试:

d3.json("http://127.0.0.1:5000/get-data").then(
  function(d){
    console.log(d);
    document.getElementById("d3-write-here").innerHTML = d;
  })

【讨论】:

    猜你喜欢
    • 2021-09-28
    • 1970-01-01
    • 2021-07-11
    • 2017-08-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多