简体   繁体   English

Pass python flask object into jQuery or JavaScript

[英]Pass python flask object into jQuery or JavaScript

I have following jQuery which modifies my html code:我有以下 jQuery 修改了我的 html 代码:

$('input[name="date-format"]').change(function () {
    if ($(this).val() == '0') {
        $(".date-range").html(`<div class="eu-input">
                                    <label>Date from</label><input name="eu-date-from">
                                    <label>Date to</label><input name="eu-date-to">
                                </div>`);
    }
    else if ($(this).val() == '1') {
        $(".date-range").html(`<div class="us-input">
                                    <label>Date from</label><input name="us-date-from">
                                    <label>Date to</label><input name="us-date-to">
                                </div>`);
    }
});

On the backend however, I have python flask and I am trying to pass flask-wtf form within the modified html.然而,在后端,我有 python flask,我试图在修改后的 html 中传递 flask-wtf 形式。 Plain html and python code on the backend would look like this:后端的普通 html 和 python 代码如下所示:

<div class="eu-input">
    <label>Date from</label>
    {{ form.eu_dates() }}
    <label>Date to</label>
    {{ form.eu_dates() }}
</div>


@app.route('/', methods=["GET", "POST"])
def home():
    form = MyForm()
    return render_template('index.html', form=form)

I am struggling to pass the python object into the JavaScript code and then include within the new html content.我正在努力将 python object 传递到 JavaScript 代码中,然后包含在新的 ZFC35FDC70D5FC69D2698Z83A8E 内容中。 Thanks for your help.谢谢你的帮助。

I'm not sure what are you trying to accomplish, my guess is that you want to change the date format based on user choice between:我不确定您要完成什么,我的猜测是您想根据用户选择更改日期格式:

  1. DD.MM.YYYY DD.MM.YYYY
  2. MM.DD.YYYY MM.DD.YYYY

And you have two form field, one for the US format and the other for the EU format.您有两个表单域,一个用于美国格式,另一个用于欧盟格式。

If this the case you can render the two fields and wrap them in a div as follows:如果是这种情况,您可以呈现两个字段并将它们包装在 div 中,如下所示:

    <div id="us-date-container">
        {{ form.us_dates() }}
    </div>

    <div id="eu-date-container">
        {{ form.eu_dates() }}
    </div>

and toggle their visibility using jQuery or JavaScript:并使用 jQuery 或 JavaScript 切换它们的可见性:

$('input[name="date-format"]').change(function () {
    if ($(this).val() == '0') { // show EU format
        $("#eu-date-container").show();
        $("#us-date-container").hide();
    }
    else if ($(this).val() == '1') { // show US format
        $("#eu-date-container")[0].hide();
        $("#us-date-container")[0].show();
    }
});

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

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