从HTML访问flask变量 [英] flask variable access from HTML

查看:81
本文介绍了从HTML访问flask变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

app.py

@app.route('/cma/connect', methods=['GET', 'POST'])
def connect_management():
    user = request.form.get('all_classes')
    print('user:', user)
    return str(user)
@app.route('/')
def index():
   return render_template('app.html',
                           all_classes=default_classes)

app.html

<select name="selected_cma" class="form-control" id="all_classes">

                      {% for o in all_classes %}
                      <option  value="{{ o }}" selected>{{ o }}</option>
                      {% endfor %}   
                  </select> 
                </div>
                <div class="form-group col-xs-3">
                  <label for="all_entries">the manager</label>

                    <button class="form-control" id="button" onclick="connect()">the reciever</button>
                    <p id="countdown"></p>

app.html中的

js代码

js code inside the app.html

 $('#button').click( function(event) {
                event.preventDefault();

                $.post("/cma/connect", $('#form').serialize(), function(data) {
                    //alert(data);
                    countdown = $("#countdown");
                    countdown.append(data + "<br/>");
                });
            });

我的结果

user: None
127.0.0.1 - - [19/Jun/2020 10:03:11] "POST /cma/connect HTTP/1.1" 200 -

我想要什么

user: (the selected option from the dropdown menu)

总结问题

我想将选定的选项返回到我的flask api中以进一步使用并显示它,而无需转到新的 tab

i want to get the selected option back to my flask api for further usage and display it without going to a new tab

有什么新方法吗?

推荐答案

如果您不想在代码中使用< form> (这很奇怪),则可以尝试

If you don't want to use <form> in code (which is very strange) then you can try

<script>
    $('#button').click( function(event) {
        event.preventDefault();

        var selected = $("#all_classes :selected").val();

        alert("selected: " + selected);

        $.post("/ra/connect", {"selected_cma": selected}, function(data) {
            //alert(data);
            countdown = $("#countdown");
            countdown.append(data + "<br/>");
        });
    });
</script>

其余部分应该相同.

JavaScript 发送 {"selected_cma":selected} ,因此 Flask 必须在 form.get('selected_cma')

@app.route('/cma/connect', methods=['GET', 'POST'])
def connect_management():
    user = request.form.get('selected_cma')
    print('user:', user)
    return str(user)

<select name="selected_cma" class="form-control" id="all_classes">
    {% for o in all_classes %}
     <option  value="{{ o }}" selected>{{ o }}</option>
    {% endfor %}   
</select> 
</div>

<div class="form-group col-xs-3">
     <label for="all_entries">the manager</label>
     <button class="form-control" id="button">the reciever</button>
     <p id="countdown"></p>

并且不需要 onclick ="onclick()" ,因为 $('#button').click(...)已经分配了功能.而且,如果您具有某些功能 onclick(),那么它还会带来其他一些问题.

And don't need onclick="onclick()" because $('#button').click(...) already assign function. And if you have some function onclick() then it can makes some other problems.

最低工作代码

from flask import Flask, request, render_template_string

app = Flask(__name__)

@app.route('/')
def index():
    return render_template_string('''<html>
<script src="https://code.jquery.com/jquery-3.5.1.min.js" integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"></script>

   <select name="selected_class" class="form-control" id="all_classes">
   {% for o in all_classes %}
      <option  value="{{ o }}" selected>{{ o }}</option>
   {% endfor %}   
   </select> 
   <button class="form-control" id="button">Get gateways</button>

<p id="countdown"></p>

<script>
    $('#button').click( function(event) {
        event.preventDefault();

        var selected = $("#all_classes :selected").val();

        alert("selected: " + selected);

        $.post("/ra/connect", {"selected_cma": selected}, function(data) {
            //alert(data);
            countdown = $("#countdown");
            countdown.append(data + "<br/>");
        });
    });
</script>
</html>''', all_classes=['Hello', 'World'])

@app.route('/ra/connect', methods=['GET', 'POST'])
def connect_management():
    print(request.form)
    print(request.data)
    user = request.form.get('selected_cma')
    print('user:', user)
    return str(user)

app.run()


顺便说一句::上一个问题: 查看全文

登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆