Getting posted data from ajax to flask server and displaying template
Edit
I don't think my question qualifies a duplicate (at not obvious to a lay user like me). Either way let me clarify what I need, and my present kludgy solution.
A user event (ctrl v) sends data to the server using a 'POST' method. The only reason I am using ajax is to get pasted images from the clipboard.
On the server a flask/python function reads the data, and eventually displays the results in the form render_template('index.html',results=func(request.form))
Surely this can't be that tricky. From the comments below I came up with a makedo solution. ajax posts to server, python saves data to a file, returns the filename
to ajax. The done
function in ajax is modified to redirect to a url containing the filename.
done(function(filename) {
window.location.href = "/scan/"+filename;
});
And finally I have a route for
@app.route('/scan/<filename>',methods=['POST'])
def somefunc(filename):
#stuff
return render_template("index.html",results=...)
I have no idea whether this is a good way to do this or even safe.
Original post
In this simple example, a script listens for a 'paste' (ctrl+v) event, and then routes it to a flask/python function. But for some reason the last render_template call is never executed.
html & javascript
<body>
Press Ctrl+V (page must be focused)
<br /><br />
{%if msg %}
{{ msg }}
{% endif %}
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type=text/javascript>
//Listen for a Ctr+V event
document.addEventListener('paste', function (e) {send_data(e);},false);
send_data = function (e) {
var fd = new FormData();
fd.append('data', "Mytest");
$.ajax({
type: 'POST',
url: '/pastetest',
data: fd,
processData: false,
contentType: false
}).done(function() {
console.log('sent to server');
});
e.preventDefault();
};
</script>
</body>
Flask/python
@app.route('/')
def index():
print("yo")
return render_template('paste4.html',msg="Waiting")
@app.route('/pastetest',methods=['POST'])
def image_upload():
print("On the server")
print(request.form)
return render_template('paste4.html',msg="All Done") #<-- Doesn't execute??
The output on the terminal confirms that everything went smoothly with the 'POST'.
* Serving Flask app "pasteapp"
* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
yo
127.0.0.1 - - [06/Nov/2017 21:25:37] "GET / HTTP/1.1" 200 -
On the server
ImmutableMultiDict([('data', 'Mytest')])
127.0.0.1 - - [06/Nov/2017 21:25:42] "POST /pastetest HTTP/1.1" 200 -
But the last 'All Done' is never displayed on the page. I just can't understand what's going here.
链接地址: http://www.djcxy.com/p/71908.html