这个问题在这里已有答案:
我想使用Ajax调用服务器端函数。
我找到了PHP in this post的简单示例。我认为如果我们可以包含这个相同的例子,但是对于Python / Flask MVC框架,社区将会改进。
这是View端的ajax代码,名为test.html:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
function create () {
$.ajax({
url:"test1", //the page containing python script
type: "post", //request type,
dataType: 'json',
data: {registration: "success", name: "xyz", email: "[email protected]"},
success:function(result){
console.log(result.abc);
}
});
}
</script>
这将是Controller上的Python代码:
@app.route('/test', methods=['GET','POST'])
def test():
return render_template("test.html", brand = brand)
@app.route('/test1', methods=['GET','POST'])
def test1():
if registration == "success":
return json.dump({"abc":'successfuly registered'});
删除视图函数的参数。使用request.form
访问发布的数据。使用jsonify
返回JSON响应。视图必须返回每个执行路径的响应。
@app.route('/test1', methods=['GET', 'POST'])
def test1():
if request.form.get('registration') == 'success':
return jsonify({'abc': 'successfuly registered'})
return jsonify({'abc': 'registration unsuccessful'})