Ajax POST 请求到 Flask

问题描述 投票:0回答:1

我是 Flask 和 JS 的新手,想要创建一个简单的 Web 应用程序。快完成了,我只需要完成最后一个功能。我使用用 JS 编写的秒表,然后单击按钮(它嵌套在表单内,但我想通过 Json 将变量从 JS 脚本(创建此秒表并返回时间)传递到烧瓶。

目前我尝试了以下方法:

function charge_time(btn_id)
{
    clearInterval(state.interval);
    $.ajax({
        type: "POST",
        dataType: "json",
        url: "/timer/",
        data: { time : state.time, id: btn_id },
        success: function(data) {
          console.log(data)
        }
      });
    state.time = 0;
    stopwatch.classList.replace("active", "inactive");
}

我点击此按钮后调用此函数:

<td>
                        <button type="button" class="btn btn-warning" id="{{ task.task_id }}" onclick="charge_time(this.id)"><i class="fa fa-clock-o"></i></button>
</td>

因此,我还传递一个按钮的参数 id,该按钮是唯一的任务 id,因为该数据表示为表格,我需要知道哪个任务时间需要更新。

这是我的烧瓶路线功能

@app.route('/timer/', methods=["POST"])
@login_required
def timer():
    """ Handle saving timer"""
    if request.method == "POST":
        time = request.get_data()
        print(time, file=sys.stderr)
        task_id = request.form['task_id']
        if not time:
            return render_template("error_handling.html", message="Could not charge time")
        db.execute("UPDATE tasks SET charge = ? WHERE task_id = ? AND user_id = ?", time, task_id,session["user_id"])
        return redirect('/')

结果是我收到 400 Bad 请求,并且 print 函数返回类似这样的内容(“b'time=3&id=9”),我一直在寻找一种以不同方式发送 json 的方法,或者传递两个变量(如这将给出两个变量,task_id 和 time,但发生了其他错误)。

如果您能提供有关如何正确执行此操作的任何提示,我将不胜感激。大多数答案都与使用 ajax 和 html 端的表单有关,但我不能嵌套它们,因为一个人将整个表用于另一个目的。

python json flask post
1个回答
0
投票

由于您使用的是 POST 方法,因此您应该通过 URL 参数获取数据,而不是使用查询参数,如下所示:

@app.route('/timer/<time>/<id>', methods=["POST"])
def timer(time, id):
    # Use time and id here
© www.soinside.com 2019 - 2024. All rights reserved.