[英]How to send html data to flask without form
我知道您可以使用jquery中的$.ajax()
類的調用輕松地將表單數據發送到flask,但是我需要的是一種使用元素(例如<p>
標記)將數據發送到flask服務器的方法。
例如:test.html
<p data-rep='testentry' class='qtemp'>Entry00</p>
<p data-rep='testentry01' class='qtemp'>Entry01</p>
index.js
$(document).ready(function(){
$('.qtemp').on('click',function(){
var layout = $(this).data('rep');
$.ajax({
url: 'workstation',
type: 'POST',
data: layout
});
});
});
main.py
@app.route('/workstation',methods=['GET','POST'])
def workstation(data):
layout = data
return render_template('station.html',target=layout)
運行此應用程序:
station.html
layout
變量(我添加了一條打印語句,但它不起作用,甚至嘗試將其寫入文件中) 我嘗試過的
index.js
,將data: layout
替換為data: JSON.stringify(layout)
然后在.main.py
,將layout = data
替換為layout = request.args.get('data')
。 不用說,所有這些都不起作用
注意:不能使用html表單
您需要修改ajax
以確保您從Python路由接收到JSON
驗證結果。 另外,為了存儲從ajax調用返回的數據,您必須使用flask.request.args
通過鍵名訪問值:
在index.js
:
$(document).ready(function(){
$('.qtemp').on('click',function(){
var layout = $(this).data('rep');
$.ajax({
url: "/workstation",
type: "get",
data: {layout: layout},
success: function(response) {
var new_html = response.html;
},
});
});
});
在main.py
:
@app.route('/workstation')
def workstation():
layout = flask.request.args.get('layout')
return flask.jsonify({'html':flask.render_template('station.html',target=layout)})
編輯:您可以將從ajax
請求中獲得的值存儲在flask.session
,然后重定向到所需的頁面。 為此,創建一條附加路徑來保存該值,然后在ajax
success
函數的主體中利用window.location.replace
:
在index.js
:
$(document).ready(function(){
$('.qtemp').on('click',function(){
var layout = $(this).data('rep');
$.ajax({
url: "/update_layout",
type: "get",
data: {layout: layout},
success: function(response) {
window.location.replace('/workstation');
},
});
});
});
在main.py
import string, random
app.secret_key = ''.join(random.choice(string.printable) for _ in range(20))
#secret_key needed for session implementation
@app.route("/update_layout")
def update_layout():
flask.session['layout'] = flask.request.args.get('layout')
return flask.jsonify({'success':'True'})
@app.route('/workstation', methods=['GET'])
def workstation():
return flask.render_template('station.html',target = flask.session['layout'])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.