簡體   English   中英

Flask 在沒有提交按鈕的情況下獲取復選框值

[英]Flask get checkbox value without submit button

我試圖在沒有提交的情況下獲取 Flask 中復選框的值。

這是我的 app.py:

from flask import Flask, render_template, request

app = Flask(__name__)

@app.route('/', methods=['GET', 'POST'])
def index():
    if request.form.get('c_check')=="0":
        print('success: 0')
        checked=''
    elif request.form.get('c_check')=="1":
        print('success: 1')
        checked='checked'
    return render_template('index.html')

這是我的 JavaScript 切換復選框:

function hello() {
    if (document.querySelector('input').value=='0') {    
        document.querySelector('input').value='1'
        console.log('value 1');
    }
    else {
        document.querySelector('input').value='0'
        console.log('value 0');
    }
}

這是我的索引。html:

<form method="post" action="">

    <div class="form-check form-switch">
        <input class="form-check-input btn-lg" 
        name="c_check" 
        value="0" 
        type="checkbox" 
        role="switch" 
        id="flexSwitchCheckChecked" 
        onclick="hello()"
        >
        
        <label class="form-check-label btn-lg" 
        for="flexSwitchCheckChecked"></label>
        <input type="submit">
    </div>
</form>

<script src="{{url_for('static', filename= 'js/hello.js')}}"></script>

我想要

  1. 移除提交按鈕
  2. 當我點擊復選框時,Python 應該收到復選框值,0 或 1。

當前代碼僅在我單擊提交按鈕時返回 1。 解決方案應該是我完全刪除提交按鈕並讓 Python 監聽值變化並實時打印。

我對socketio解決方案持開放態度,但我不知道該怎么做。

您只需要為此更改客戶端; 使用 AJAX。 這是使用純 JavaScript 的最簡單示例:

 function ajaxRequest() { const checked = document.getElementById("mycheckbox").checked; console.log("Sending data to the server that the checkbox is", checked); // Use the XMLHttpRequest API const xhttp = new XMLHttpRequest(); xhttp.onload = function() { console.log("Result sent to server;"). } xhttp,open("POST", "/"; true). xhttp;send(); }
 <label for="mycheckbox">Check or uncheck this box:</label> <input id="mycheckbox" type="checkbox" onchange="ajaxRequest()" />

顯然,該示例不起作用,因為沒有服務器,但這是 AJAX 的示例,一旦用戶單擊復選框,就會出現復選框。

為此,您需要向輸入添加一個偵聽器。 完全刷新的表單提交可能會導致用戶體驗不佳,因此我們將使用 JS 發送異步請求以將數據 POST 到路由,然后從響應中讀取數據。

這是一個概念驗證演示,它一直使用 JSON,現在是 AJAX 的標准:

index.html

<body>
  <input type="checkbox" />
  <div class="result"></div>
  <script>
    document
      .querySelector("input")
      .addEventListener("click", e => {
        fetch("http://127.0.0.1:5000/", {
            method: "POST",
            headers: {
              "Accept": "application/json",
              "Content-Type": "application/json"
            },
            body: JSON.stringify({
              c_check: Number(e.target.checked)
            })
          })
          .then(res => {
            if (!res.ok) {
              throw Error(res.status);
            }

            return res.json();
          })
          .then(({data: {val}}) => {
            console.log(val);
            const res = document.querySelector(".result");
            res.innerText = `client got: ${val}`;
          })
          .catch(err => console.error(err))
        ;
      })
    ;
  </script>
</body>

app.py

from flask import (
    Flask, jsonify, render_template, request
)

app = Flask(__name__)

@app.route("/", methods=["GET", "POST"])
def index():
    if request.method == "GET":
        return render_template("index.html")

    val = request.json.get("c_check")
    print(val)
    return jsonify({"data": {"val": val}})
    
if __name__ == "__main__":
    app.run(host="127.0.0.1", port=5000, debug=True)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM