[英]Getting flask model objects to javascript using ajax
就上下文而言,我正在編寫一個學生個性化的每周日歷,並使用 flask-sqlalchemy 創建了一個數據庫,用於存儲我所有的課程及其信息。 我當前的目標是將數據庫與我的 html 表鏈接。
So I have a class Lessons in models.py which I filled with data and I have no problem using it in my html or python code, but I would like to use it in a javascript function and it seems so complex just to link both.
根據我的閱讀,Ajax 可能是我的問題的解決方案,但經過多次嘗試,我無法解決任何問題。 我將我的課程列表 jsonify,但是當我在 ajax function 中收到它時,它無法使用。 知道我做錯了什么嗎?
我的 js function:
/**
* Displays the user's lessons
*/
function displayLessons(){
$.ajax({
url: '/get_lessons',
type: 'GET',
success: function(lessons) {
for(lesson in lessons){
// I'll need to get the user too but that's for later
if(lesson.years == user.year && lesson.studies == user.studies){
// haven't tried this out yet but the idea is there
document.getElementById(lesson.jour+'-'+lesson.start_hour).textContent = lesson.title
}
}
}
});
我的路線:
@app.route('/get_lessons', methods=['GET'])
def get_lessons():
if request.method == 'GET':
lessons = Lessons.query.all()
return jsonify(lessons)
注意:我是初學者,這是我的第一篇文章,我的描述可能不夠清楚,在這種情況下,我很樂意回答您的問題。
它通過將我的路線更改為:
@app.route('/get_lessons', methods=['GET'])
def get_lessons():
if request.method == 'GET':
lessons = Lessons.query
return jsonify(list(map(lambda x: x.to_dict(), lessons)))
我只需要pip install sqlalchemy-serializer
並在我的 models.py 中:
from sqlalchemy_serializer import SerializerMixin
更改: class Lessons(db.Model, SerializerMixin):
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.