简体   繁体   中英

how do I take user input without refreshing the page in flask?

how do I take user input without refreshing the page in flask? This i've tried so far:

@app.route('/', methods=['POST'])
def my_form_post():
    result = request.form['text']

    return result
@app.route('/')
def hello_world():
  return render_template('index.html')

index.html:

<form method="POST">
    <h1>Input something here!</h1>
    <input name="text">
    <input type="submit">
</form>

but the problem is it loads another page every time they click submit. I've also looked at other stack overflow questions but nothing helped.

This is a small example of how you can request input, send it to the server via AJAX using the POST method and receive the answer. Remember there are several different ways to do this. Which one you use depends on your requirements.

The code on the server side should look familiar to you. The jsonify function converts the transferred parameters into JSON-compliant output.

from flask import jsonify

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/greet', methods=['POST'])
def greet():
    if 'name' in request.form:
        name = request.form['name']
        return jsonify(message=f'Hello, {name}.')
    return '', 400

Version 3.5.x of the jQuery API is integrated in the following code. You can of course also write your own code. However, I advise you to use this option and make your work a little easier.

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Simple Example</title>
  </head>
  <body>
    <form name="my-form">
      <input type="text" name="name" />
      <input type="submit" />
    </form>
    <p id="message"></p>

    <script 
        src="https://code.jquery.com/jquery-3.5.1.min.js" 
        integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" 
        crossorigin="anonymous"
    ></script>
    <script type="text/javascript">
      $(document).ready(function(){
        $("form[name='my-form']").submit(function(event) {
          event.preventDefault();
          $.post("/greet", $(this).serialize())
            .done(function(data) {
              $("#message").html(data.message);
            })
            .fail(function() {
              $("#message").html("An error has occurred.");
            });
        });
      });
    </script>
  </body>
</html>

A form is used to request the data from the user. After loading the page, the form is queried based on the name. An event listener for a submit event is registered for the form.
If the user now clicks on the button, a submit event is fired, which is received by the registered listener.
It must now be ensured that the form is not sent as usual, but that further processing is done manually. This is done with the line event.preventDefault() .
Afterwards the data of the form is requested and serialized. The formatting takes place in the manner "name1=value1&name2=value2...", which corresponds to the encoding type "application/x-www-form-urlencoded".
There are also other ways of formatting the data, such as JSON. But for the example you have given, a transmission as "application/x-www-form-urlencoded" seems the easiest.
The data is now transmitted via HTTP POST in which the data is sent to the relevant address within the request body.
If communication with the server is successful, the result is transferred to the corresponding element on the page.

There are other examples like the ones I wrote you in the comments. Look around and you will achieve your goal.

A note at the edge. This platform is suitable for solving problems that can occur, for example, when programming. It is not the right place for documentation, tutorials or architectural questions. If you come across issues with further attempts, there are a lot of people here who will help 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