搜尋

首頁  >  問答  >  主體

根據第一個過濾器的條目更新下拉過濾器的值

我正在開發一個 Flask 應用程序,用於過濾 Mysql 資料庫表的值,並根據第一個下拉列表的選定值,它將更新第二個下拉列表的值。最後返回一些數據

現在程式碼正在工作,但程式碼中似乎存在錯誤,這樣當我從第一個下拉列表中進行新選擇時,它將用第一個下拉列表的值以及預期的值填充第二個下拉列表第二個下拉清單的值

它不應該這樣做,我希望它只用預期值填充第二個下拉列表,而不是將第一個下拉列表的值與其一起添加。

這是我的燒瓶應用程式程式碼:

from flask import jsonify, request
from flask import Flask, render_template  
import mysql.connector

app = Flask(__name__)

# Configure MySQL connection
cnx = mysql.connector.connect(
  host="xxxxxxx",
  user="xxxxxxxxx",
  password="xxxxxxxxx",
  database="xxxxxxxxxx")


@app.route('/', methods=['GET', 'POST'])
def index():
    try:
        cursor = cnx.cursor()
        query = "SELECT topic FROM text_table"
        cursor.execute(query)
        data = [row[0] for row in cursor.fetchall()] # Get the first column of all rows
        cursor.nextset() # consume any unread result
        cursor.close()


        if request.method == 'POST':
            selected_topic = request.form.get('selected_topic') # Get the selected topic from the form
            if selected_topic:
                cursor = cnx.cursor()
                query = "SELECT sub_topic FROM text_table WHERE topic = %s"
                cursor.execute(query, (selected_topic,))
                sub_topics = [row[0] for row in cursor.fetchall()] # Get the sub topics for the selected topic
                cursor.nextset()
                selected_sub_topic = request.form.get('selected_sub_topic') # Get the selected sub topic from the form
                if selected_sub_topic:
                    query = "SELECT text FROM text_table WHERE topic = %s AND sub_topic = %s"
                    cursor.execute(query, (selected_topic, selected_sub_topic))
                    result = cursor.fetchone()[0] # Get the value of the text for the selected sub topic
                    cursor.nextset()
                    cursor.close()
                    return render_template('index.html', topics=data, selected_topic=selected_topic, sub_topics=sub_topics, selected_sub_topic=selected_sub_topic, result=result)

                cursor.close()
                return render_template('index.html', topics=data, selected_topic=selected_topic, sub_topics=sub_topics)

        return render_template('index.html', topics=data)

    except Exception as e:
        # Return an error message if there's an exception
        return jsonify(error=str(e)), 500


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

這是我的 html 程式碼,帶有一點 JavaScript

<!DOCTYPE html>
<html>
  <head>
    <title>Drop Down Filter</title>
    <script>
        function updateSubTopics() {
            var selectTopic = document.getElementById("selected_topic");
            var selectSubTopic = document.getElementById("selected_sub_topic");
            var selectedTopicValue = selectTopic.value;

            // Send a POST request to update the sub topic options
            var xhr = new XMLHttpRequest();
            xhr.open('POST', '/');
            xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
            xhr.onload = function() {
                if (xhr.status === 200) {
                    // Update the sub topic options
                    selectSubTopic.innerHTML = xhr.responseText;

                    // Check if the currently selected sub topic is valid for the new selected topic
                    var subTopicOptions = selectSubTopic.options;
                    var foundSelectedSubTopic = false;
                    for (var i = 0; i < subTopicOptions.length; i++) {
                        if (subTopicOptions[i].value === selectSubTopic.value) {
                            foundSelectedSubTopic = true;
                            break;
                        }
                    }
                    if (!foundSelectedSubTopic) {
                        selectSubTopic.value = "";
                    }
                }
                else {
                    console.log('Request failed. Returned status of ' + xhr.status);
                }
            };
            xhr.send('selected_topic=' + selectedTopicValue);
        }
    </script>
  </head>
  <body>
    <form method="POST">
      <select name="selected_topic" id="selected_topic" onchange="updateSubTopics()">
        {% for topic in topics %}
          <option value="{{ topic }}"
            {% if selected_topic == topic %}selected{% endif %}>
            {{ topic }}
          </option>
        {% endfor %}
      </select>
      <select name="selected_sub_topic" id="selected_sub_topic">
        {% for sub_topic in sub_topics %}
          <option value="{{ sub_topic }}"
            {% if selected_sub_topic == sub_topic %}selected{% endif %}>
            {{ sub_topic }}
          </option>
        {% endfor %}
      </select>
      <input type="submit" value="Filter">
    </form>
    {% if result %}
      <h1>{{ result }}</h1>
    {% endif %}
  </body>
</html>

謝謝,任何幫助將不勝感激

#
P粉033429162P粉033429162520 天前585

全部回覆(1)我來回復

  • P粉141035089

    P粉1410350892023-09-09 10:14:00

    當您在過濾後發送模板回應時,會出現此問題。

    您已經渲染了index.html,但是從該行更改選擇選項時,您也在渲染index.html。

    這基本上意味著您將所有 html 程式碼貼到 select 元素中,您可以透過在瀏覽器中檢查來檢查該元素。

    在我看來,應該要做的是你應該只發送一個Python字典作為子主題的回應。

    if selected_topic:
        cursor = cnx.cursor()
        query = "SELECT sub_topic FROM text_table WHERE topic = %s"
        cursor.execute(query, (selected_topic,))
        sub_topics = [row[0] for row in cursor.fetchall()] # Get the sub topics for the selected topic
        cursor.nextset()
        selected_sub_topic = request.form.get('selected_sub_topic') # Get the selected sub topic from the form
        if selected_sub_topic:
            query = "SELECT text FROM text_table WHERE topic = %s AND sub_topic = %s"
            cursor.execute(query, (selected_topic, selected_sub_topic))
            result = cursor.fetchone()[0] # Get the value of the text for the selected sub topic
            cursor.nextset()
            cursor.close()
            return render_template('index.html', topics=data, selected_topic=selected_topic, sub_topics=sub_topics, selected_sub_topic=selected_sub_topic, result=result)
    
            cursor.close()
            return sub_topics

    成功取得字典後,回應將是格式的,因此需要將其解析為json。然後,您可以使用 JS 循環來建立循環並將其附加到您的 sub_topic 選擇項目中。

    if (xhr.status === 200) {
        selectSubTopic.options.length = 0;
        
        var subTopicOptions = JSON.parse(xhr.responseText);
    
        for (var i = 0; i < subTopicOptions.length; i++) {
            var option = document.createElement('option');
            option.text = subTopicOptions[i];
            option.value = subTopicOptions[i];
            selectSubTopic.appendChild(option);
        }
        
        // Check if the currently selected sub topic is valid for the new selected topic
        var subTopicOptions = selectSubTopic.options;
        var foundSelectedSubTopic = false;
        for (var i = 0; i < subTopicOptions.length; i++) {
            if (subTopicOptions[i].value === selectSubTopic.value) {
                foundSelectedSubTopic = true;
                break;
            }
        }
        if (!foundSelectedSubTopic) {
            selectSubTopic.value = "";
        }
    }
    else {
        console.log('Request failed. Returned status of ' + xhr.status);
    }

    回覆
    0
  • 取消回覆