如何将数据发送到Flask服务器?

时间:2020-03-16 16:41:48

标签: javascript python html python-3.x flask

我是使用flask或JS的新手,因为那样,我找不到一种方法来做自己想做的事情。 我使用Flask(在python中)创建了一个网络服务器,并且它使用index.html作为主页,我想每隔几秒钟(也许1-3秒)将数据更新到服务器。问题是,我没有任何形式可以使用,甚至没有查询,而且我不知道我还能使用什么。我要发送的数据是一个小字符串,稍后将保存在服务器主机上。

<body>
    <center>
        <button onmousedown="sendDirectionKey('^')">^</button>
        ...
    </center>
</body>

<script>
    function sendDirectionKey(Key) 
    {
        ...
        sendData(data_string);
    }

    function sendData(data)
    {
        ...
    }
</script>

1 个答案:

答案 0 :(得分:1)

一种简单的现代解决方案是fetch() API:

function sendData(data)
{
  const body = new FormData();
  body.append("key", data);
  return fetch("/receive", {method: "POST", body, credentials: "include"});
}

Python端的等效接收器类似于

@app.route("/receive", methods=["POST"])
def receive():
    print(request.form)  # should have a `key` key