将数组从Flask传递到Javascript以创建下拉菜单选项

时间:2015-05-26 12:17:02

标签: javascript python arrays flask

我是Flask和Javascript的新手。我正在尝试上传文件并使用其中一个列作为下拉菜单中的选项。请纠正我错在哪里。

以下是代码:

烧瓶中:

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>

我在控制台上收到以下错误: ReferenceError:my_script未定义

1 个答案:

答案 0 :(得分:1)

有两个问题。

第一个是你没有在你的视图中传递汽车列表 ITEM.insert(len(ITEM),list(buff[0]))

/meta

这可能看起来像这样:

@app.route('/meta')
def drop_down():
   return render_template('drop_down.html')

第二个问题是你的javascript无法访问该列表,除非你在调用函数时传递它。

HTML

@app.route('/meta')
def drop_down():
   cars = ["Volvo","Ferrari","Audi","BMW","Mercedes","Porche","Saab","Avanti"]
   return render_template('drop_down.html',
                          names=cars)

的javascript

<body onload="my_script({{ names }})">

编辑:

处理视图的函数是需要传递数据的函数。您还可以使用上传文件中已评论的部分,该部分会使用必要的数据调用function my_script(names){ console.log('script called.'); var cars = names; ... ,但这并不是一个好的&#34;方法

您需要将数据提供给render_template...视图,方法是将其存储在数据库中,从此函数中的文件中读取数据或将其存储在会话中。这样您就可以将数据与模板一起传递