Currently, I am attempting to write the backend and front end of a program that records an array of information on every keypress and sends it to a Python backend. The Python backend then sends back a response (that will probably be a boolean) that the JavaScript responds to.
I believe I have figured out how to send an array to the Python back end via this video and this Stack Overflow post: https://www.youtube.com/watch?v=zJdQxS3ZpNI, Pass array to ajax request in $.ajax(). I have not yet worked out the exact processing; currently, I'm just following the tutorial to figure out what to do. As such, response function is just a placeholder.Below is the code that I have currently:
index.html
:
<div id="response"></div>
<script
src="https://code.jquery.com/jquery-3.4.1.js"
integrity="sha256-WpOohJOqMqqyKL9FccASB9O0KwACQJpFTUBLTYOVvVU="
crossorigin="anonymous"></script>
<script type="text/javascript">
$.ajax({
url: "/_get_data/",
type: "POST",
data: {data_array:data_array},
success: function(resp){
$('div/response').append(resp.data);
}
});
</script>
from flask import Flask, render_template, jsonify
app = Flask(__name__)
@app.route('/')
def index():
return render_template('index.html')
@app.route('/_get_data/', methods=['POST'])
def _get_data():
myList = ['Element1','Element2','Element3']
return jsonify({'data': render_template('response.html',myList=myList)})
response.html
:
<ul>
{% for elem in myList %}
<li>{{elem}}</li>
{% endfor %}
</ul>
According to the tutorial, the line: return jsonify({'data': render_template('response.html',myList=myList)}) is the key. He said that the myList=myList part is the response, and 'data' and response.html is the data recieved. My question is, how do I access the data the JavaScript sent in my Python server, process it, then send it back in separate lines? I'm not really clear what "render_template" is doing, or how myList=myList works. Any explanations? Thanks!