将数组从Flask传递给Javascript,为下拉菜单创建选项 [英] Passing array from Flask to Javascript to create options for drop down menu
问题描述
以下是代码:
Flask:
从瓶子导入瓶子,render_template,重定向,url_for,请求,flash,send_from_directory $ b $从werkzeug中导入secure_filename
import os
导入pandas为pd
导入numpy为np
导入json
UPLOAD_FOLDER ='uploads /'
ALLOWED_EXTENSIONS = set(['csv'])
app = Flask(__ name__)
app.config ['UPLOAD_FOLDER'] = UPLOAD_FOLDER
$ b $ def allowed_file(filename):
return '。'in filename和filename.rsplit('。',1)[1] ALLOWED_EXTENSIONS
@ app.route('/',methods = ['GET','POST'])
def upload_file():
if request.method =='POST':
file = request.files ['data_file']
如果file和allowed_file(file.filename) :
文件名= secure_filename(file.filename)
file.save(os.path.join(app.config [ 'UPLOAD_FOLDER'],filename))
data = pd.read_csv(os.path.join(app.config ['UPLOAD_FOLDER'],filename))
names = data ['some_column ']
return redirect(url_for('drop_down',names = names))
#return render_template('drop_down.html',names = names)
return render_template('file_upload.html' )
@ app.route('/ meta')
def drop_down():
return render_template('drop_down.html')
$ c $ 函数my_script()
< {
console.log('script called。'); 沃尔沃,法拉利,奥迪,宝马,奔驰,保时捷,萨博,阿凡提];
var cars = {{names | safe}};
console.log('cars assigned。');
$ b $函数make_drop_down(list_of_names,element_id){
select_elem = document.getElementById(element_id)
if(select_elem){
for(var i = 0; i< ; list_of_names.length; i ++){
var option = document.createElement('option');
option.innerHTML = list_of_names [i];
option.value = list_of_names [i];
select_elem.appendChild(option);
}
}
};
console.log(Making Drop Downs !!);
make_drop_down(汽车,'drop_down_1');
make_drop_down(汽车,'drop_down_2');
console.log(Made Drop Downs !!);
};
html:
<!DOCTYPE html>
< html>
< head>
< script type =text / javascriptsrc =static / drop_down.js>< / script>
< title> DROP DOWN< / title>
< / head>
< body onload =my_script()>
< select id =drop_down_1>
< option>选择选项1< / option>
< / select>
< / br>< / br>
< select id =drop_down_2>
< option>选择选项2< / option>
< / select>
< / body>
< / html>
我在控制台上得到以下错误:
ReferenceError:my_script未定义有两个问题。
第一个是你是不要在您的视图中传递汽车列表handeling / meta
@ app.route('/ meta')
def drop_down():
return render_template('drop_down.html')
这应该看起来像这样:
@ app.route('/ meta ')
def drop_down():
cars = [沃尔沃,法拉利,奥迪,宝马,奔驰,保时捷,萨博,阿凡提]
return render_template('drop_down.html',
names = cars)
第二个问题是,你的javascript将无法访问列表,除非你在调用函数中传递它。
$ b html
< body on load =my_script({{names}})>
javascript
function my_script(names){
console.log('script called。');
var cars = names;
...
编辑:
处理视图的函数是需要传递数据的函数。您也可以使用上传文件的已注释部分,该文件使用必要的数据调用 render_template ...
,但这并不是一个好的方法。
您需要将数据提供给 drop_down()
视图,方法是将其存储在数据库中,从这个函数中的文件中读取数据或者将它存储在会话中。这样你就可以将数据和模板一起传递给
I am new to Flask and Javascript. I am trying to upload a file and use one of its columns as options in the drop down menu. Please correct me where I am wrong.
Here are the codes:
Flask:
from flask import Flask, render_template, redirect, url_for, request, flash, send_from_directory
from werkzeug import secure_filename
import os
import pandas as pd
import numpy as np
import json
UPLOAD_FOLDER = 'uploads/'
ALLOWED_EXTENSIONS = set(['csv'])
app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
def allowed_file(filename):
return '.' in filename and filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS
@app.route('/', methods=['GET', 'POST'])
def upload_file():
if request.method == 'POST':
file = request.files['data_file']
if file and allowed_file(file.filename):
filename = secure_filename(file.filename)
file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
data = pd.read_csv(os.path.join(app.config['UPLOAD_FOLDER'], filename))
names = data['some_column']
return redirect(url_for('drop_down', names=names))
#return render_template('drop_down.html', names=names)
return render_template('file_upload.html')
@app.route('/meta')
def drop_down():
return render_template('drop_down.html')
Javascript:
function my_script(){
console.log('script called.');
//var cars = ["Volvo","Ferrari","Audi","BMW","Mercedes","Porche","Saab","Avanti"];
var cars = {{ names|safe }};
console.log('cars assigned.');
function make_drop_down(list_of_names, element_id){
select_elem = document.getElementById(element_id)
if(select_elem){
for(var i = 0; i < list_of_names.length; i++) {
var option = document.createElement('option');
option.innerHTML = list_of_names[i];
option.value = list_of_names[i];
select_elem.appendChild(option);
}
}
};
console.log("Making Drop Downs!!");
make_drop_down(cars, 'drop_down_1');
make_drop_down(cars, 'drop_down_2');
console.log("Made Drop Downs!!");
};
html:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="static/drop_down.js"></script>
<title>DROP DOWN</title>
</head>
<body onload="my_script()">
<select id="drop_down_1">
<option>Choose Option 1</option>
</select>
</br></br>
<select id="drop_down_2">
<option>Choose Option 2</option>
</select>
</body>
</html>
I get the following error on the console:
ReferenceError: my_script is not defined
解决方案 There are two problems.
The first one is that you are not passing the list of cars in your view handeling /meta
@app.route('/meta')
def drop_down():
return render_template('drop_down.html')
This should probably look something like this:
@app.route('/meta')
def drop_down():
cars = ["Volvo","Ferrari","Audi","BMW","Mercedes","Porche","Saab","Avanti"]
return render_template('drop_down.html',
names=cars)
The second problem is that your javascript won't be able to access the list, unless you pass it in your call to the function.
html
<body onload="my_script({{ names }})">
javascript
function my_script(names){
console.log('script called.');
var cars = names;
...
Edit:
The function that handles the view is the function that needs to pass the data. You could also use the commented away part of your upload file, which calls render_template...
with the necessary data, but this doesn't feel as a "nice" approach.
You need to make the data available to your drop_down()
view, either by storing it in a database, reading the data from the file in this function or by storing it in the session. So that you can pass the data along with the template
这篇关于将数组从Flask传递给Javascript,为下拉菜单创建选项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!