我一直在用Flask开发一个web服务器应用程序。到目前为止,我创建了一个小框架,用户可以使用画布和javascript在图像中绘制一些方框。我在javascript中将框信息和图像信息保存在一个向量中。但是,所有这些数据必须提交并存储在服务器端的数据库中。因此,我有一个按钮来提交所有这些内容,但我不知道如何检索我拥有的javascript数据,即:框和图像信息。在
有没有可能让javascript信息像这样提交?我提出了一些想法,比如在隐藏的HTML元素中打印信息,或者使用AJAX将信息发送到服务器,但是我不认为这些是在Flask中处理这个问题的“正确”方法。那么,有人有主意吗。下面是我的部分代码,可能与理解我的问题有关:
在模型.py:我这里的类有点不同:Blindmap=Image,Label=box。我的数据库是用SQLAlchemy建模的。在
blindmap_label = db.Table('blindmap_label',
db.Column('blindmap_id', db.Integer, db.ForeignKey('blindmap.id', ondelete = 'cascade'), primary_key = True),
db.Column('label_id', db.Integer, db.ForeignKey('label.id', ondelete = 'cascade'), primary_key = True))
class Blindmap(db.Model):
__tablename__ = 'blindmap'
id = db.Column(db.Integer, primary_key = True)
description = db.Column(db.String(50))
image = db.Column(db.String)
labels = db.relationship('Label', secondary = blindmap_label, backref = 'blindmaps', lazy = 'dynamic')
def __init__(self, label = None, **kwargs):
if label is None:
label = []
super(Blindmap, self).__init__(**kwargs)
def add_label(self, label):
if label not in self.labels:
self.labels.append(label)
db.session.commit()
def __repr__(self):
return '<Blindmap %r:>' % (self.id)
class Label(db.Model):
__tablename__ = 'label'
id = db.Column(db.Integer, primary_key = True)
name = db.Column(db.String(50))
x = db.Column(db.Integer)
y = db.Column(db.Integer)
w = db.Column(db.Integer)
h = db.Column(db.Integer)
def __repr__(self):
return '<Pair %r:>' % (self.id)
我的控制器信息:
^{pr2}$
您需要做的是使用AJAX,这是一种在页面加载到客户端浏览器后,使用JavaScript从服务器“异步”发送请求和获取响应的技术。 事实上,AJAX代表异步JavaScript和XML(尽管它不一定非得是完全异步的,也不一定要使用XML作为数据交换格式)。这是访问webapi的标准方法,比如使用Flask构建的一个api,它通过url(代表路由的url)公开在后端检索和持久化对象的能力。在
现代浏览器一致地公开XMLHttpRequest构造函数(MDN documentation),该构造函数可用于创建允许页面加载后与Web服务器通信的对象。在
为了提高跨浏览器的兼容性和代码的可维护性,可以使用JavaScript框架将XMLHttpRequest“包装”成自己的抽象。为了这个目的,我多年来一直在有效地使用jQuery。特别是,在您的例子中,您需要jQuery.ajax方法(或者,对于POST操作,它是速记jQuery.post)。在
不过,我会给你举一个小例子,说明如何使用vanilla JS来执行这样的请求,这样即使在使用框架的情况下,也能理解浏览器中的情况:
有关使用XMLHttpRequest的更多详细信息,请参阅MDN。在
试试jQuery ajax:
Rest是在服务器端使用请求.json['imageData']并将其存储在数据库中。在
^{pr2}$相关问题 更多 >
编程相关推荐