繁体   English   中英

在 Python Flask 应用程序中使用下拉选项过滤(使用 JavaScript)

[英]Filter with Drop-Down Options in Python Flask App (with JavaScript)

我正在尝试使用下拉列表来过滤表格中的结果。 我试图让它与 addEventListener('click') 一起工作,但我一直坚持如何使它完全正常工作。 我想我很接近但缺少一些东西。

任何人都可以帮助提供一个解决方案,以便在单击下拉列表中的国家/地区值时,它会过滤表中具有相应国家/地区值的所有那些? 这将需要工作,以便使用多个列上的多个下拉菜单。

在此处输入图像描述

Python

app = Flask(__name__)
test_data = [['jack', 23, 'china', 'https://www.google.com'],
             ['jill', 22, 'canada', 'https://www.cnn.com'],
             ['john', 24, 'canada', 'https://www.cnn.com'],
             ['jane', 30, 'australia', 'https://www.bbc.com']]

test_df = pd.DataFrame(test_data, columns=['name', 'age', 'country', 'link'])
test_df = test_df.to_dict(orient='index')
@app.route("/hello")
def index():
    return render_template("index.html", test_df=test_df)

HTML :在索引中。html

<div class="container">
    <label for="country">Countries</label>
    <form class="form">
        <div class="form__group">
            <select id="country" name="country" data-dropdown>
                <option value="">Please select a country</option>
                <option value="australia">Australia</option>
                <option value="canada">Canada</option>
                <option value="china">China</option>
            </select>
        </div>
    </form>
</div>

<table class="table">
    <tbody id="myTable">
    </tbody>
</table>

JavaScript :在 index.html 在脚本标签内

var mydata = JSON.parse('{{ test_df|tojson }}');
var countrySelector = document.getElementById('country');
// but what next?

buildTable(mydata)
function buildTable(data) {
    var table = document.getElementById('myTable')
    table.innerHTML = ''
    for (var key in data) {
        var row = `<tr>
                    <td>${data[key].name}</td>
                    <td>${data[key].age}</td>
                    <td><a href="${data[key].link}" target='_blank'>${data[key].country}</a></td>
               </tr>`
        table.innerHTML += row
    }
}

使用 select 元素的更改事件来监视用户在选择中的更改。
以下示例向您展示如何按国家/地区过滤行。 为了更容易过滤 JavaScript 中的行,它们不是作为字典传递,而是使用df.values.tolist()作为列表传递。

from flask import (
    Flask, 
    render_template
)
import pandas as pd

app = Flask(__name__)

@app.route('/')
def index():
    test_df = pd.DataFrame(
        [
            ['jack', 23, 'china', 'https://www.google.com'],
            ['jill', 22, 'canada', 'https://www.cnn.com'],
            ['john', 24, 'canada', 'https://www.cnn.com'],
            ['jane', 30, 'australia', 'https://www.bbc.com']
        ],
        columns=['name', 'age', 'country', 'link']
    )
    return render_template('index.html', test_df=test_df.values.tolist())
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Index</title>
  </head>
  <body>
    <div class="container">
      <label for="country">Countries</label>
      <form class="form">
        <div class="form__group">
          <select id="country" name="country" data-dropdown>
            <option value>Please select a country</option>
            <option value="australia">Australia</option>
            <option value="canada">Canada</option>
            <option value="china">China</option>
          </select>
        </div>
      </form>
    </div>

    <table class="table">
      <tbody id="myTable">
      </tbody>
    </table>

    <script type="text/javascript">

      function buildTable(data) {
          const table = document.getElementById('myTable')
          table.innerHTML = data.map(row => {
            let [name, age, country, link] = row;
            return `<tr>
                <td>${name}</td>
                <td>${age}</td>
                <td><a href="${link}" target='_blank'>${country}</a></td>
              </tr>`;
          }).join('');
      }

      const data = {{ test_df|tojson }};
      const countrySelector = document.getElementById('country');
      countrySelector.addEventListener('change', evt => {
        const value = evt.target.value;
        if (value) {
          buildTable(data.filter(row => {
            let [name, age, country, link] = row;
            return country === value
          }));
        } else {
          buildTable(data);
        }
      });

      buildTable(data)

    </script>

  </body>
</html>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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