我有一个带有3个不同值的下拉select2字段。但是,如何将所选的值从下拉列表发送到我的烧瓶程序中的变量?以下是我的以下代码和我迄今所做的尝试
<script type="text/javascript">
//var hugo=document.getElementById("fmea").value;
$(document).on('submit','#form',function(e)
{
e.preventDefault();
$.ajax({
type:'POST',
url:'/index',
data:{
event:$("#event").val(),
context:$("#context").val(),
//'fmea[]':$("#fmea.select2").val()
//fmea:$('.test').select2(content[0])
fmea:JSON.stringify(fmea)
},
//traditional:true,
success:function()
{
draw();
}
})
});
</script>select2
<script>
var content = [
{id: 0, text: "Event1"},
{id: 1, text: "Event2 "},
{id: 2, text: "Event4"},
];
$(".test").select2({
data:content,
// minimumInputLength: 2,
width: '35%',
multiple:true,
placeholder:"Enter another event",
// templateResult:formatState
});和html代码
<form method="post" id="form" enctype="multipart/form-data">
<input type="text" name="event" id="event" class="btn" placeholder="Event" >
<input type="text" name="context" id="context" class="btn" placeholder="Context" >
<input type ="text" name="fmea" id="fmea" class="btn test" placeholder="Select another Event">
<br>
<br>
<button type="submit" class="btn btn-primary" onclick="hide()" >Show Graph</button>
</form>和蟒蛇
fmea=request.form.get("fmea")我很容易获得前两个输入值,但是fmea标记不返回任何值。如果你能告诉我如何得到所选的价值,我会非常感激的。
通过db连接编辑,我正在获取存储在python中的数据。这个列表我想传递给select2,这样用户就可以选择这个值了。
app.py
@application.route("/autocomplete",methods=["POST","GET"])
def autocomplete():
#getting topic names
q1="MATCH (n:Topic) RETURN n"
nodes=neo4j_session.run(q1)
node_result = nodes.data()
node_raw=list()
for d in node_result:
for key in d:
node_raw.append(d[key])
nodes=list()
for i in node_raw:
nodes.append(i['Name'])
return jsonify(nodes)
@application.route('/index', methods=["POST","GET"])
def index():
if request.method == "POST":
df=pd.DataFrame()
topic=request.form.getlist("topic")
topic=''.join(str(x) for x in topic)
print(topic)
query=get_final_query(topic)
results=neo4j_session.run(query).data()
df=pd.DataFrame.from_dict(results)
#df=df.drop_duplicates()
df=df.reset_index(drop=True)
return render_template("dashboard.html",query=query,tables=[df.to_html(classes="table table-striped table-hover table-sm",header=True)])
return render_template("dash.html")select2现在
<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
<script type="text/javascript">
(function(contentUri, dataUri) {
$(document).ready(function() {
$('select[name="topic"]').select2({
ajax: {
url: "/index",
dataType: 'json'
},
width: '35%',
multiple: true,
placeholder: 'Enter another event'
});
$('form[name="myform"]').bind(function(evt) {
//evt.preventDefault();
$.ajax({
method: 'POST',
url: dataUri,
data: $(this).serialize()
}).done(function(data) {
$('output[name="result"]').html(data.selected.join(','));
})
});
});
})({{ url_for('.autocomplete') | tojson }});发布于 2022-02-15 22:31:51
下面的示例向您展示了如何使用AJAX向服务器提交具有像您这样的选择框的表单。
一旦触发提交事件,就会通过serialize函数对整个表单进行相应格式化,然后发送。
由于您已经选择了可以选择多个选项的选择字段的变体,因此request.form对象提供的request.form包含一个元组列表。在这种情况下,您可以使用request.form.getlist(...)查询使用选择框名称包含的值,正如您从其他输入字段中已经知道的那样。返回值对应于具有所选值的列表。这些参数通过指定类型参数自动转换。
烧瓶(app.py)
from flask import Flask
from flask import (
render_template,
request,
jsonify
)
app = Flask(__name__)
@app.route('/')
def index():
return render_template('index.html')
@app.route('/data', methods=['POST'])
def data():
events = request.form.getlist('events', type=int)
return jsonify(selected=events)HTML (模板/index.html)
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Select2 Example</title>
<link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
</head>
<body>
<form name="my-form" method="post">
<select name="events"></select>
<button type="submit">Submit</button>
</form>
<output name="result"></output>
<script
src="https://code.jquery.com/jquery-3.6.0.min.js"
integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4="
crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
<script type="text/javascript">
(function(uri) {
$(document).ready(function() {
const content = [
{id: 0, text: 'Event 1'},
{id: 1, text: 'Event 2'},
{id: 2, text: 'Event 3'},
];
$('select[name="events"]').select2({
data: content,
width: '35%',
multiple: true,
placeholder: 'Enter another event'
});
$('form[name="my-form"]').submit(function(evt) {
evt.preventDefault();
$.ajax({
method: 'POST',
url: uri,
data: $(this).serialize()
}).done(function(data) {
$('output[name="result"]').html(data.selected.join(','));
})
});
});
})({{ url_for('.data') | tojson }});
</script>
</body>
</html>如果希望从python中传递selectbox条目,可以将它们传递给模板。然后在JavaScript代码中使用jinja过滤器tojson将列表转换为JavaScript数组。
from flask import Flask
from flask import (
render_template,
request,
jsonify
)
app = Flask(__name__)
@app.route('/')
def index():
items = [
{ 'id': 0, 'text': 'Event 1' },
{ 'id': 1, 'text': 'Event 2' },
{ 'id': 2, 'text': 'Event 3' },
]
return render_template('index.html', **locals())
@app.route('/data', methods=['POST'])
def data():
events = request.form.getlist('events', type=int)
return jsonify(selected=events)<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Select2 Example</title>
<link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
</head>
<body>
<form name="my-form" method="post">
<select name="events"></select>
<button type="submit">Submit</button>
</form>
<output name="result"></output>
<script
src="https://code.jquery.com/jquery-3.6.0.min.js"
integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4="
crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
<script type="text/javascript">
(function(uri, content) {
$(document).ready(function() {
$('select[name="events"]').select2({
data: content,
width: '35%',
multiple: true,
placeholder: 'Enter another event'
});
$('form[name="my-form"]').submit(function(evt) {
evt.preventDefault();
$.ajax({
method: 'POST',
url: uri,
data: $(this).serialize()
}).done(function(data) {
$('output[name="result"]').html(data.selected.join(','));
})
});
});
})({{ url_for('.data') | tojson }}, {{ items | tojson }});
</script>
</body>
</html>作为另一种选择,您还可以通过AJAX获得列表。
from flask import Flask
from flask import (
render_template,
request,
jsonify
)
app = Flask(__name__)
@app.route('/index')
def index():
return render_template('index.html')
@app.route('/content')
def content():
q = request.args.get('q', '')
items = [
{ 'id': 0, 'text': 'Event 1'},
{ 'id': 1, 'text': 'Event 2'},
{ 'id': 2, 'text': 'Event 3'},
]
results = [item for item in items if q in item['text']]
return jsonify(results=results)
@app.route('/data', methods=['POST'])
def data():
events = request.form.getlist('events', type=int)
return jsonify(selected=events)<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Select2 Example</title>
<link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
</head>
<body>
<form name="my-form" method="post">
<select name="events"></select>
<button type="submit">Submit</button>
</form>
<output name="result"></output>
<script
src="https://code.jquery.com/jquery-3.6.0.min.js"
integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4="
crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
<script type="text/javascript">
(function(contentUri, dataUri) {
$(document).ready(function() {
$('select[name="events"]').select2({
ajax: {
url: contentUri,
dataType: 'json'
},
width: '35%',
multiple: true,
placeholder: 'Enter another event'
});
$('form[name="my-form"]').submit(function(evt) {
evt.preventDefault();
$.ajax({
method: 'POST',
url: dataUri,
data: $(this).serialize()
}).done(function(data) {
$('output[name="result"]').html(data.selected.join(','));
})
});
});
})({{ url_for('.content') | tojson }}, {{ url_for('.data') | tojson }});
</script>
</body>
</html>更新
我不得不承认,我还没有和neo4j合作过。尽管如此,我还是试着想出一个解决方案,但目前我无法测试。
这样做的想法是,您请求一个条目的id和名称,给该id别名id,并将name属性重命名为text。若要进行筛选,应搜索与查询参数匹配的名称。
它根据name属性进行排序。
然后对所有结果进行迭代,每个条目被转换为一个dict。结果列表作为嵌套属性返回,用于JSON格式的结果。
def autocomplete():
q = request.args.get('q', '')
query = "MATCH (n:Topic) "\
"WHERE toLower(n.name) CONTAINS toLower($qs) "\
"RETURN id(n) AS id, n.name AS text "\
"ORDER BY n.name"
nodes = neo4j_session.run(query, qs=q)
items = [{k:v for k,v in node.items()} for node in nodes]
return jsonify(results=items)https://stackoverflow.com/questions/71127884
复制相似问题