你好,我是新人,正在用 Flask 和 Javascript 构建一个应用程序。我在从 Flask do JavaScript 发送数据时遇到问题。
我在routes.py中有代码
@app.route('/mapaa',methods=['GET','POST'])
def mapa():
user_id = current_user.get_id()
slownik = {}
if 'event_form' in request.form:
name = request.form['name_event']
all_data = Event.query.filter_by(name=name).all()
for row in all_data:
date_st_string = str(row.date_start)
date_end_string = str(row.date_end)
slownik = {'id':row.id,'date_st':date_st_string,'date_end':date_end_string,'type':row.type,'name':row.name,'len_route':row.len_route,'route':row.route}
return jsonify(slownik)
return render_template('mapaa.html', title='Mapa')
我想发送jsonify(slownik)
我的 JavaScript 代码,但我不想这样做render_template
因为它刷新页面,我需要这些数据使用 JavaScript 将其显示在地图上。我试过return jsonify(slownik)
但它返回我新页面上的数据。当用户点击时如何发送数据event_form
按钮到 JavaScript 而不刷新页面?
您可以使用ajax发送post请求,而无需刷新页面。
注意-在此之前包含 jquery
<script src="https://code.jquery.com/jquery-3.1.0.js" ></script>
JavaScript 代码
$("#id_of_btn").click(function () { // make ajax request on btn click
$.ajax({
type: "POST",
url: "/mapaa", // url to the function
data: {
name: $("#id_of_input_tag").val(), // value of the form
},
success: function (response) {
console.log(response); // response contains the json
},
});
});
确保您不使用表单标签。
编辑:
如果您想通过表单发送更多数据,您可以使用
data: $('form').serialize()
这将获取输入标签的 name 属性并将其添加到 request.data 中
所以如果你有这个
<input type="text" id="element_id" name="username" >
您可以像这样使用 name 属性的值request.data['username']
按照这个tutorial https://www.bogotobogo.com/python/Flask/Python_Flask_with_AJAX_JQuery.php
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)