gpt4 book ai didi

javascript - 在 Flask/Javascript 中获取动态列表元素到服务器

转载 作者:行者123 更新时间:2023-12-02 16:16:10 24 4
gpt4 key购买 nike

我正在尝试编写一个非常基本的 Flask/Javascript 应用程序,它可以在每次单击“提交”按钮(并将其发送到服务器)时检查元素列表的顺序;我尝试了“request.get”的许多不同变体,但似乎找不到任何可以提取 listWithHandle 元素上任何信息的内容。

这似乎是一个简单的操作,但我对网络编程还很陌生,而且我无法解码我确定包含解决方案的文档。

有两个文件:

应用程序.py

from flask import Flask, render_template, request, redirect
app = Flask(__name__)

names = ['Ivuoma', 'Carla', 'Aly']

@app.route('/')
def hello_world():
# When "submit" button is clicked,
# print order of names to console,
# then reorder python names list and render_template.
return render_template('index.html', names=names)

if __name__ == '__main__':
app.run(debug=True)

index.html:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Sortable Test!</title>
</head>
<body>

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css"/>
<script src="http://rubaxa.github.io/Sortable/Sortable.js"></script>

<ul id="listWithHandle">
{% for name in names %}
<li><span class="my-handle">:+:</span>{{ name }}</li>
{% endfor %}
</ul>

<div>
<button class="submit">Submit</button>
</div>

<script id="sortable-script">
Sortable.create(listWithHandle, {
handle: '.my-handle',
animation: 150
});
</script>
</body>
</html>

基于已接受的答案的修复:

应用程序.py

prelim_names = ['Carla', 'Aly', 'Ivuoma']
@app.route('/', methods=['GET', 'POST'])
def hello_world():
names = request.form.getlist('handles[]')
if not names:
names = prelim_names
print('names to display', names)
return render_template('index.html', names=names)

index.html

  <form method="post">
<ul id="listWithHandle">
{% for name in names %}
<li>
<span class="my-handle">:+:</span>
<input type="hidden" name="handles[]" value="{{ name }}"/> {{ name }}
</li>
{% endfor %}
</ul>


<div>
<button class="btn btn-lg btn-primary">Submit</button>
</div>
</form>

最佳答案

{% for name in names %}
<li><span class="my-handle">:+:</span><input type="hidden" name="handles[]" value="{{ name }}"/>{{ name }}</li>
{% endfor %}

您需要提供<input>为了发送数据。

关于javascript - 在 Flask/Javascript 中获取动态列表元素到服务器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29568235/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com