Rumah > Soal Jawab > teks badan
Saya sedang membangunkan aplikasi Flask yang menapis nilai jadual pangkalan data Mysql dan berdasarkan nilai pilihan dropdown pertama, ia akan mengemas kini nilai dropdown kedua. Akhirnya pulangkan beberapa data
Sekarang kod berfungsi tetapi nampaknya terdapat pepijat dalam kod sehingga apabila saya membuat pilihan baharu daripada lungsur pertama ia mengisi lungsur kedua dengan nilai lungsur pertama serta nilai yang dijangkakan untuk lungsur kedua senaraikan nilai
Ia tidak sepatutnya melakukan ini, saya mahu ia hanya mengisi dropdown kedua dengan nilai yang dijangkakan, bukan menambah nilai dropdown pertama bersama-sama dengannya.
Ini adalah kod aplikasi kelalang saya:
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()
Ini kod html saya dengan sedikit 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>
Terima kasih, sebarang bantuan akan sangat dihargai
P粉1410350892023-09-09 10:14:00
Isu ini berlaku apabila anda menghantar respons templat selepas penapisan.
Anda telah membuat index.html, tetapi apabila menukar pilihan pemilihan daripada baris itu, anda juga sedang memaparkan index.html.
Ini pada asasnya bermakna anda menampal semua kod html anda ke dalam elemen pilihan yang boleh anda periksa dengan memeriksanya dalam penyemak imbas anda.
Pada pendapat saya, apa yang perlu dilakukan ialah anda hanya perlu menghantar kamus Python sebagai respons topik kanak-kanak.
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
Selepas berjaya mendapatkan kamus, respons akan diformatkan supaya ia perlu dihuraikan ke dalam json. Anda kemudiannya boleh menggunakan gelung JS untuk mencipta gelung dan menambahkannya pada pemilihan sub_topik anda.
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); }