简体   繁体   中英

flask python,javascript variable issue?

my flask code section that have issue main.py

from flask import Flask, render_template, url_for
import pandas as pd 
import json

app = Flask(__name__)


@app.route('/')
def home():
    df = pd.read_csv('test.csv')
    df = df.groupby('name')['marks'].sum()
    j = df.to_json(orient='index')
    return render_template("work.html",s=j)

if __name__ == "__main__":
    app.run(debug=True)

and i want to pass j into my javascript file that is look like that work.js

//pie chart
var s = {{ j|safe }};
var keys = [];
   for(var k in s) keys.push(k);
var value = [];
   for (var k in s) value.push(s[k]);

var data = [{
  values: value,
  labels: keys,
  type: 'pie'
}];

var layout = {
  height: 400,
  width: 500
};
Plotly.newPlot('myDiv1', data);

work.html

<html>
        <head>
        <meta http-equiv="content-type" content="text/html; charset=UTF-8" />
        <script src="https://cdn.plot.ly/plotly-latest.min.js"></script>
        <link rel="stylesheet" type="text/css" href="styles.css">
        </head>
        <body>
        <div class="navbar"><span>data representation with Plotly.js</span></div>

        <div class="wrapper">
            <div id="myDiv1"></div>
            <script type="text/javascript" src={{ url_for('static', filename='work.js')}}> 
            </script>
        </div>
        </body>
</html>

how to pass j variable in flask to s variable in javascript file that render with html page and show right content or say that no graph shown Thank you

You can't do that. You have to return that json in your flask method and make an ajax request from javascript.

from flask import jsonify

@app.route('/')
def home():
    j = df.to_json(orient='index')
    return jsonify(j)

I don't know if flask has something like JsonResponse as django has. If yes you should use that like: return JsonResponse(j)

$.ajax({url: "your_url", success: function(result){
    //result is what you returned from flask
}});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM