問題描述
您好,我是新手,正在使用 Flask 和 Javascript 構建應用程序.我從 Flask do JavaScript 發送數據時遇到問題.
Hello I am new and building an application in Flask and Javascript. I have a problem with sending data from Flask do JavaScript.
我在 routes.py 中有代碼
I have code in 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')
我想用 JavaScript 將 jsonify(slownik)
發送到我的代碼,但我不想用 render_template
這樣做,因為它會刷新頁面,我需要這些數據使用 JavaScript 在地圖上顯示它.我嘗試了 return jsonify(slownik)
但它在新頁面上返回了我的數據.當用戶單擊 event_form
按鈕而不刷新頁面時如何將數據發送到 JavaScript?
I want to send jsonify(slownik)
to my code in JavaScript but I dont want to do it with render_template
bacause it refresh a page and I need this data to display it on the map using JavaScript. I tried return jsonify(slownik)
but it return me the data on new page. How I can send the data when the user click event_form
button to JavaScript without refreshing page?
推薦答案
您可以使用ajax 發送post 請求而無需刷新頁面.注意 - 在此之前包含 jquery
You can use ajax for sending post request without refreshing the page. Note- include jquery before this
<script src="https://code.jquery.com/jquery-3.1.0.js" ></script>
javascript 代碼
javascript code
$("#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
},
});
});
確保你不使用表單標簽.
make sure you don't use form tag.
如果您想通過表單發送更多數據,您可以使用
If you want to send more data via forms, you could use
data: $('form').serialize()
這將獲取輸入標簽的名稱屬性并將其添加到request.data中所以如果你有這個
this will take the name attribute of input tag and add it in the request.data So if you have this
<input type="text" id="element_id" name="username" >
您可以像這樣使用 name 屬性的值 request.data['username']
按照這個 教程
You can use the value of name attribute like this request.data['username']
follow this tutorial
這篇關于如何將數據從 Flask 發送到 JavaScript?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!