简体   繁体   中英

How to send variable data form html to flask

I want to send variable data form html to flask
This is my html js code.
I can not send that variable data to the flask in that way.

<script>
        var data = "shan";
        window.location.href='{{ url_for( "move_forward" , title=data) }}';
</script>

But when I used below way I can send it

<script>
        window.location.href='{{ url_for( "move_forward" , title="shan") }}';
</script>

But finally I want to assign some value to the variable and I want to send it to the flask.
How can I do it

 @app.route("/move_forward/<title>", methods=['GET', 'POST'])
        def move_forward(title):
             print(title)

Jinja templates (the parts using {{ ... }} ) are not JavaScript.

When you call render_template , '{{ url_for( "move_forward" , title="shan") }}' gets replaced with something like '/move_forward/shan' and this is what the client receives.

When you do '{{ url_for( "move_forward" , title=data) }}' Flask/Jinja doesn't know what data is because it doesn't interact with the JavaScript, it's just trying to replace a string.

You could instead use a mixture of JavaScript and Jinja to get it working:

<script>
    var baseUrl = '{{ url_for("move_forward") }}';
    var data = "shan";
    window.location.href = baseUrl + "/" + data;
</script>

Thank you @Henry for your answer and I go trough it and do little modification to do it work.

In HTML js script I modify like bellow

var baseUrl = '{{ url_for("move_forward") }}';
var data = "shan";
window.location.href = baseUrl + "?title=" + data;

and Then I modify the Flask code like bellow.

@app.route("/move_forward", methods=['GET', 'POST'])
        def move_forward():
            if request.method == 'GET':
                title = request.args.get('title')

Now it's work perfectly. Thank you

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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