首页 > 解决方案 > 如何将坐标从 javascript 文件发送到烧瓶服务器以放入数据库?

问题描述

我有一个简单的烧瓶应用程序,它接受用户通过文本区域编写的评论,并将其发布在我的数据库“评论”的“内容”列下的数据库中:

            <div class="row">
                <form action="." method="POST">
                    <textarea name="contents" placeholder="Enter a comment" class="form-control"></textarea>
                    <input type="submit" class="btn btn-success" value="Post comment">
                </form>
            </div>

然后在服务器上:

@app.route("/", methods=["GET", "POST"])
def index():
    if request.method == "GET":
        return render_template("bulletin.html", comments=Comment.query.filter(Comment.content != ''))

    comment = Comment(content=request.form["contents"])
    db.session.add(comment)
    db.session.commit()
    return redirect(url_for('index'))

假设我在javascript中有两个变量,纬度和经度。如何将这些变量发送到我的烧瓶服务器以存储在同一个数据库表中?(假设我在表中创建了纬度和经度列)

谢谢

标签: pythonflasksqlalchemy

解决方案


首先设置 python 来接受这些信息。为要发布到的坐标创建端点

@app.route("/coords/<x>/<y>", methods=["POST"])
  def coords(x, y):
    # Have the code here to save to which ever database you use

然后让 javascript 向该 URL 发送一个发布请求。在您的示例中,您使用表单,因此使用 HTML 操作标签发布到特定 URL


推荐阅读