我一直在使用Flask开发一个webserver应用程序。到目前为止,我创建了一个小框架,用户可以使用canvas和javascript在图像中绘制一些框。我将框信息保存在javascript中的矢量以及图像信息中。但是,必须提交所有这些数据并将其存储在服务器端的数据库中。因此,我有一个按钮来提交所有这些内容,但我不知道如何检索我的javascript数据,即:盒子和图像信息。
是否可以像这样提交javascript信息?我想出了一些想法,比如在隐藏的HTML元素中打印信息,或者使用AJAX将信息发送到服务器,但我不认为这些是处理这个问题的“正确”方法。烧瓶。那么,有没有人有想法。以下是我的部分代码,可能与理解我的问题相关:
Models.py:我的类在这里有点不同:Blindmap = Image,Label = boxes。我的数据库使用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)
我的控制器信息:
@app.route('/')
@app.route('/index')
def index():
blindmaps = db.session.query(Blindmap).all()
return render_template("index.html",
title = 'Home',
blindmaps = blindmaps)
@app.route('/new', methods = ['GET', 'POST'])
def new():
form = BlindmapForm()
if request.method=="POST":
if form.validate_on_submit():
blindmap = Blindmap(description=form.description.data)
redirect(url_for('index'))
return render_template("new.html",
title = 'New Blindmap',
form=form)
答案 0 :(得分:3)
尝试jQuery ajax:
function upload() {
// Generate the image data
var img= document.getElementById("myCanvas").toDataURL("image/png");
img = img.replace(/^data:image\/(png|jpg);base64,/, "")
// Sending the image data to Server
$.ajax({
type: 'POST',
url: '/upload', // /new
data: '{ "imageData" : "' + img + '" }',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (msg) {
// On success code
}
});
}
Rest是使用request.json [&#39; imageData&#39;]在服务器端上传图像数据并将其存储在数据库中。
img = request.json['imageData'] # Store this in DB (use blob)
答案 1 :(得分:1)
你要做的就是使用AJAX技术,以及#34;异步&#34;在使用JavaScript在客户端浏览器上加载页面后,发送请求并从服务器获取响应。 事实上,AJAX代表异步JavaScript和XML(尽管它不一定非必须完全异步,也不必将XML作为数据交换格式)。这是访问Web API的标准方法,例如您使用Flask制作的API,它通过URL(代表路由的那些)公开检索和持久化后端对象的能力。
现代浏览器始终公开XMLHttpRequest构造函数(MDN documentation),该构造函数可用于创建允许页面在加载后与Web服务器通信的对象。
为了提高跨浏览器兼容性和代码可维护性,您可以使用“#34; wrap&#34; XMLHttpRequest有自己的抽象。为此,我多年来一直在高效地使用jQuery。特别是,在您的情况下,您需要jQuery.ajax方法(或者,对于POST操作,它是速记jQuery.post)。
但是,我将举例说明如何使用vanilla JS执行此类请求,这样即使使用框架,您也可以了解浏览器中发生的情况:
// Create an instance of the XHR object
var postNewObject = new XMLHttpRequest();
// Define what the object is supposed to do once the server responds
postNewObject.onload = function () {
alert('Object saved!');
};
// Define the method (post), endpoint (/new) and whether the request
// should be async (i.e. the script continues after the send method
// and the onload method will be fired when the response arrives)
postNewObject.open("post", "/new", true);
// Send!
postNewObject.send(/* Here you should include the form data to post */);
// Since we set the request to be asynchronous, the script
// will continue to be executed and this alert will popup
// before the response arrives
alert('Saving...');
有关使用XMLHttpRequest的详细信息,请参阅MDN。