I've made a simple Flask project with one input and this input has to be returned on the main page with AJAX.
my Html code:
<!DOCTYPE HTML>
<html>
<body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script type="text/javascript" src="{{ url_for('static', filename='script.js') }}"></script>
<div>
<div id="questionary">
<form action='/process' method="POST" autocomplete="off">
<div>
<input type="text" name="question" id = "question" placeholder="Une question?">
<button type="submit"> Pose ta question :) </button>
</div>
</form>
</div>
<div>
<p id="response"></p>
</div>
</body>
</html>
my Ajax:
$(document).ready(function() {
$('form').on('submit', function(event) {
$.ajax({
data : {
question : $('#question').val(),
},
type : 'POST',
url : '/process'
})
.done(function(data) {
$('#response').text(data.output).show();
});
event.preventDefault();
});
});
My Flask:
from flask import Flask, render_template, request, jsonify
import json
app = Flask(__name__)
@app.route('/')
def homepage():
return render_template('main.html')
@app.route('/process', methods=['POST'])
def process():
user_question = request.form['question']
print(user_question)
return jsonify({'response' : user_question})
if __name__ == '__main__':
app.run
Ajax is in /static, html in /templates. Desired output is the question asked displayed under the form.
Work if you change:
$('#response').text(data.output).show();
by:
$('#response').text(data['response']).show();
data is a json object and this is the proper way to access its values.
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.