// some movie data
var movies = {
'title': movie_title,
'release_date': movie_release_date
}
$.ajax({
url: Flask.url_for('my_function'),
type: 'POST',
data: JSON.stringify(movies), // converts js value to JSON string
})
.done(function(result){ // on success get the return object from server
console.log(result) // do whatever with it. In this case see it in console
}
from flask import request, jsonify, render_template
import sys
@app.route("/function_route", methods=["GET", "POST"])
def my_function():
if request.method == "POST":
data = {} // empty dict to store data
data['title'] = request.json['title']
data['release_date'] = request.json['movie_release_date']
// do whatever you want with the data here e.g look up in database or something
// if you want to print to console
print(data, file=sys.stderr)
// then return something back to frontend on success
// this returns back received data and you should see it in browser console
// because of the console.log() in the script.
return jsonify(data)
else:
return render_template('the_page_i_was_on.html')
我是如何使用javascript发出的ajax请求来实现这一点的。我认为最简单的方法也是使用JQuery,因为使用纯javascript可能会更加冗长。
Flask.url需要JSGlue,基本上让我们使用Flask的 url_,但使用javascript。查找它,易于安装和使用。否则我想你可以用url替换它,例如'/function\u url'
然后在服务器端,您可能会得到这样的结果:
我认为要点是在jquery、flask的request.json()和jsonify()函数中查找ajax请求。
相关问题 更多 >
编程相关推荐