簡體   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