简体   繁体   中英

Rendering changes to html templates using flask

I am trying to use python's flask api and javascript to build a web application. As a simple example I wanted to have a text input box that will print the users input after they submit. However, when I run this using flask run and input some text nothing changes except that I get redirected from "/5000" to "/5000/?input=text" where text is the user input.

Why don't I see "You wrote: text" below the input box?

My code looks something like this:

app.py:

@app.route('/')
def render_home():
    return render_template("base.html")

update.js:

function update() {
    var new_input = document.getElementById("input");
    document.getElementById("demo").innerHTML = "You wrote: " + new_input.value;
}

base.html:

<body>
<form>
    <label for="input">Example Input:</label><br>
    <input type="text" name="input" onchange="update()"><br>
</form>

<p id="demo"></p>

<script type="text/javascript" src="static/js/update.js"></script>
</body>

So Flask is registering the 'submit' as a GET request, which is why it's appearing in the URL. if you're hoping to have this information parsed in the backend you can use the request submodule so to actually recieve the data by the Python instance, using something like request.args to receive it as a key: value pair.

from flask import Flask, request

@app.route('/', methods=['GET'])
def render_home():
    req = request.args
    print(req)
    return render_template("base.html")

It's normal that the app adds the query param when you press Enter, but I think your JS function is not working because getElementById('input') will return null since your input has no id set on it. Try setting the id on the input like <input id="myInput" and use document.getElementById('myInput')

Also you have a typo in the JS func. Your input is in new_input but you are using new_factor later.

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