Pyscript无法从db.json获取数据问题求助
修复PyScript无法从JSON Server获取数据的问题
修复后的完整代码
<!DOCTYPE html> <html> <head> <title>Students Data</title> <meta charset="utf-8"> <link rel="stylesheet" href="https://pyscript.net/latest/pyscript.css" /> <script defer src="https://pyscript.net/latest/pyscript.js"></script> <!-- Add axios library --> <script defer src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script> </head> <body> <div id="students-data" style="margin: 20px;"> <h2>Students Data:</h2> <py-placeholder id="students-placeholder">Loading students data...</py-placeholder> </div> <py-script> import js from pyodide.ffi import create_proxy async def fetchStudentsData() -> dict: """Fetches the students data from the server.""" try: response = await js.axios.get("http://localhost:4000/students") if response.status == 200: # 适配JSON Server返回的数组结构,包装为原代码预期的格式 return {"students": response.data} else: return {} except Exception as e: js.console.error("Fetch error:", e) return {} def displayStudents(data: dict) -> None: """Displays the students data in the HTML.""" studentsPlaceholder = js.document.querySelector("#students-placeholder") studentsHtml = "" if data and "students" in data and len(data["students"]) > 0: for student in data["students"]: studentInfo = f"ID: {student['id']}<br>Name: {student['name']}<br>Age: {student['age']}<br>Grade: {student['grade']}" studentsHtml += f"<p>{studentInfo}</p>" else: studentsHtml = "<p>No data available</p>" studentsPlaceholder.outerHTML = studentsHtml async def onDocumentLoad() -> None: """Called when the document loads.""" js.console.log("Document loaded.") studentsData = await fetchStudentsData() displayStudents(studentsData) # 正确绑定页面加载事件 js.window.onload = create_proxy(onDocumentLoad) </py-script> </body> </html>
关键错误修复点
- 异步请求处理错误:Axios的
get方法返回Promise,必须用async/await异步获取响应,原代码同步调用会拿到Promise对象而非实际数据。 - Python缩进错误:Python对缩进严格,原代码函数内的代码块未缩进,直接触发语法错误导致脚本无法执行。
- DOM/Console引用错误:在PyScript中访问浏览器的
document、console必须通过js对象,比如js.document、js.console,直接调用会找不到这些对象。 - 函数调用错误:
displayStudents是Python定义的函数,不能用js.displayStudents调用,直接调用即可。 - 页面加载事件绑定错误:PyScript中绑定浏览器异步事件需要用
create_proxy包装函数,否则无法正确触发;原代码直接赋值window.onDocumentLoad不会自动执行。 - 响应状态码判断错误:Axios响应对象的状态码是
response.status,不是response.status_code。 - 字符串语法错误:原代码中
studentInfo的f-string换行导致语法错误,需合并为完整字符串。 - 数据结构适配:JSON Server请求
/students返回的是学生数组,而非包含students键的对象,修复后将响应数据包装为符合原代码预期的结构。
内容的提问来源于stack exchange,提问作者PazM
相关产品推荐
相关产品推荐

