我希望将每个具有值的键发布到Flask框架中的函数,以将它们存储在MySQL数据库中。我可以这样做吗?
JQuery的
$.ajax({
type: "POST",
url: "{{url_for('savedata')}}", // Function to send data
data: sessionStorage.serializeArray(),
success: function(data) {
window.location.replace("/quit"); // Redirect to another page after saving data
}
});
app.py
conn = mysql.connect()
cursor = conn.cursor()
@app.route("/savedata",methods=["POST"])
def savedata():
sql = "INSERT INTO data_table "
data = ""
for (var i = 0; i < sessionStorage.length; i++) {
var item = sessionStorage.getItem(sessionStorage.key(i));
data += "item " + "VARCHAR(255)"
}
sql += data
cursor.execute(sql)
答案 0 :(得分:0)
sessionStorage无法转换为数组
你可以这样做:
var localdata = {};
for ( var i = 0, len = localStorage.length; i < len; ++i ) {
localdata[localStorage.key( i )] = localStorage.getItem( localStorage.key( i ) );
}
和ajax:
data:localdata;
答案 1 :(得分:0)
扩展madalin的答案,我想指出你不能直接从Flask使用sessionStorage
,而只能使用JS代码。您可以做的是一个AJAX POST请求,其中您将来自sessionStorage的键/值作为JSON字符串,然后使用request.json
或更好request.get_json访问Flask视图中的JSON:
AJAX:
$.ajax({
url: "{{ url_for('savedata', _external=True) }}",
type: 'POST',
dataType: 'json',
contentType: 'application/json;charset=UTF-8',
accepts: {
json: 'application/json',
},
data: JSON.stringify(localdata), // see madalin's answer
...
})
烧瓶视图:
@app.route("/savedata",methods=["POST"])
def savedata():
your_json_as_dict = request.get_json()
...