繁体   English   中英

统计 JS 前端的 html 按钮点击次数并将其发送到 flask 后端

[英]Counting html button clicks in JS front end and sending it to flask backend

我正在尝试跟踪在我的 flask 应用程序中单击按钮或下拉菜单的次数并将其发送回 python 后端,以便我可以输入数据库。 我不断得到 null 的价值,我似乎无法弄清楚。

new.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <form method = "POST">
        <button type="button" id = "numberclicks" name = "numberclicks" onClick="onClick()">Click me</button>
        <p>Clicks: <a id="clicks" name ="clicks" placeholder = 0 >{{clicks|safe}}</a></p>
        <button type="submit">Login</button>
    </form>
    </div>
    <script>
        var clicks = 0;
        function onClick() {
           clicks += 1;
           document.getElementById("clicks").innerHTML = clicks; 
           console.log(clicks)
        }   
        </script>

</body>
</html>

应用程序.py

from flask import Flask,render_template,request

import json

app = Flask(__name__)



# turn this into calss and import to record who is logged in to the session aka. user then take log data and make relationship to tables
# HOW MANY TIMES USER VISITED THE VISIT PAGE!!! 



@app.route('/', methods=['POST', 'GET'])
def signUpUser():
    if request.method == "POST":
        click = request.args.get('clicks',type = int)
        return json.dumps({'status':'OK','click':click})
    return render_template("new.html")

if __name__ == "__main__":
    app.run(debug=True)
function onClick() {
  clicks += 1;
  document.getElementById("clicks").innerHTML = clicks;
  console.log(clicks);
  fetch("/", {
    headers: {
      Accept: "application/json",
      "Content-Type": "application/json",
    },
    method: "POST",
    body: JSON.stringify({clicks}),
  });
}

您可以使用 XMLHttpRequest object 将点击次数异步发送到 flask 后端。

const xhr = new XMLHttpRequest();
xhr.open("POST", "/", true);
xhr.onload = () => {
    if (xhr.status === 200) {
        ...do whatever you want...
    }
}

const data = new FormData();
data.append("clicks", clicks);

xhr.send(data);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM