简体   繁体   中英

how can I get variable from javascript using flask

So I have set up app.py, index.js, index.html in appropriate folder as flask suggests. Index.html gets rendered as when app.py runs then index.html runs index.js which grabs input data from user. I am trying to send this input and send it to python where I can call an API, grab data, and work with it however I cannot think of a way to do this.

my app.py:

import os
from flask import Flask, render_template, jsonify, request, redirect
app = Flask(__name__)

# This will run upon entrance
@app.route("/")
def home():
    return render_template("index.html")

@app.route("/stock_data")
def get_stock_data():
    # called from index.js Plot function

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

and here is my javascript code:

console.log("everythin works fine.")
d3.select("#stocklabelsubmit").on("click", submitted)

function submitted(){
    d3.event.preventDefault();

    // grab label inputted.
    var inputted_label = d3.select("#stockInput").node().value;

    d3.select("#stockInput").node().value = "";

    Plot(inputted_label);
};


function Plot(input){
    var url = "full url"
    // when this function is called call /stock_data function!!
    // data is what is returned from python
    d3.json(url).then(function(data){

    })
}

Everything works fine, when I console log inputted_label at the end of function submitted it works. Now I want to send inputted_label variable to /stock_data. Thanks in advance!

var url = "/stock_data"

This needs to be a valid URL, not just the path to the Flask endpoint. That means it must start with "http://" or "https://" and include a domain. For development purposes, "http://localhost/stock_data" will work. If you ever deploy this to a server, you will want to create a configuration file so that the host name can be configured depending on what environment you are running in.

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