我编写了一个 server.py 文件,可以保存学生的姓名、索引号和平均成绩。当我运行client.html文件并输入数据并单击添加学生时,它说学生已成功添加,但是当我输入他的索引以使用获取学生功能时,它说404学生未找到。 p>
这是server.py文件代码:
from flask import Flask, request, jsonify import pickle app = Flask(__name__) try: with open('students.pickle', 'rb') as f: students = pickle.load(f) except FileNotFoundError: students = {} @app.route("/") def index(): with open("client.html") as f: return f.read() @app.route('/add_student', methods=['POST']) def add_student(): name = request.form.get('name') surname = request.form.get('surname') index = request.form.get('index') grade = request.form.get('grade') students[index] = {'name': name, 'surname': surname, 'index': index,'grade': grade} with open('students.pickle', 'wb') as f: pickle.dump(students, f) return jsonify(message='Student added successfully'), 201 @app.route('/get_student/<int:index>', methods=['GET']) def get_student(index): student = students.get(index) if student: return jsonify(student) else: return 'Student not found', 404 if __name__ == '__main__': app.run(host='localhost', port=8000, debug=True)
这是 client.html 文件代码:
<!DOCTYPE html> <html> <head> <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> <script> $(document).ready(function() { function getStudent() { var index = $("#index").val(); $.ajax({ type: "GET", url: "http://localhost:8000/get_student/" + index, success: function(data) { $("#student-info").text(JSON.stringify(data)); }, error: function() { $("#student-info").text("Student not found"); } }); } function addStudent() { var data = new FormData(); data.append("name", $("#name").val()); data.append("surname", $("#surname").val()); data.append("index", $("#index").val()); data.append("grade", $("#grade").val()); $.ajax({ type: "POST", url: "http://localhost:8000/add_student", data: data, processData: false, contentType: false, success: function(data) { $("#add-student-result").text("Student added"); }, error: function() { $("#add-student-result").text("Error adding student"); } }); } $("#get-student-form").submit(function(e) { e.preventDefault(); getStudent(); }); $("#add-student-form").submit(function(e) { e.preventDefault(); addStudent(); }); }); </script> </head> <body> <form id="get-student-form"> <label for="index">Index:</label> <input type="text" id="index" name="index"> <button type="submit">Get Student</button> </form> <div id="student-info"></div> <br> <form id="add-student-form"> <label for="name">Name:</label> <input type="text" id="name" name="name"> <br> <label for="surname">Surname:</label> <input type="text" id="surname" name="surname"> <br> <label for="index">Index:</label> <input type="text" id="index" name="index"> <br> <label for="grade">Grade:</label> <input type="text" id="grade" name="grade"> <br> <button type="submit">Add Student</button> </form> <div id="add-student-result"></div> </body> </html>
在 html 页面中,您为两个元素指定了相同的 id(索引设置框和获取框),因此代码仅查找第一个元素,因此字典中的索引将等于“ " 并且代码找不到它。
编辑:另一个错误是索引必须是字符串,在get函数中必须是字符串。 [只需执行index = str(index)]
希望有帮助。