首页  >  问答  >  正文

根据第一个过滤器的条目更新下拉过滤器的值

我正在开发一个 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粉033429162408 天前519

全部回复(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
  • 取消回复