Aktualisieren Sie den Wert des Dropdown-Filters basierend auf dem ersten Filtereintrag
P粉033429162
P粉033429162 2023-09-08 17:44:19
0
1
561

Ich entwickle eine Flask-Anwendung, die die Werte einer MySQL-Datenbanktabelle filtert und basierend auf dem ausgewählten Wert des ersten Dropdowns den Wert des zweiten Dropdowns aktualisiert. Endlich ein paar Daten zurückgeben

Jetzt funktioniert der Code, aber es scheint einen Fehler im Code zu geben, der dazu führt, dass, wenn ich eine neue Auswahl aus dem ersten Dropdown-Menü treffe, das zweite Dropdown-Menü mit dem Wert des ersten Dropdown-Menüs sowie dem erwarteten Wert für das zweite Dropdown-Menü gefüllt wird Listenwerte

Das sollte nicht der Fall sein. Ich möchte, dass nur das zweite Dropdown-Menü mit dem erwarteten Wert gefüllt wird und nicht der Wert des ersten Dropdown-Menüs hinzugefügt wird.

Das ist mein Flaschenanwendungscode:

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()

Das ist mein HTML-Code mit ein wenig 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>

Vielen Dank, wir freuen uns über jede Hilfe

P粉033429162
P粉033429162

Antworte allen(1)
P粉141035089

当您在过滤后发送模板响应时,会出现此问题。

您已经渲染了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);
}
Neueste Downloads
Mehr>
Web-Effekte
Quellcode der Website
Website-Materialien
Frontend-Vorlage