将下拉列表中的select2值发送到烧瓶



我有一个下拉的select2字段,其中包含3个不同的值。但是,我如何将下拉列表中的选定值发送到烧瓶程序中的变量?这是我的以下代码和我迄今为止尝试的

<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>

选择2

<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>

和python

fmea=request.form.get("fmea")

我很容易得到前两个输入值,但是fmea标记返回None。如果你能给我一个如何获得所选值的提示,我将不胜感激。

编辑通过数据库连接,我正在获取存储在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")

现在选择2

<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 }});

下面的示例向您展示了如何使用AJAX向服务器提交带有类似您的选择框的表单。

一旦触发提交事件,整个表单就会通过serialize函数进行相应的格式化,然后发送
由于您选择了选择字段的变体,其中可以选择多个选项,因此request.form对象提供的ImmutableMultiDict包含元组列表。在这种情况下,您可以使用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(templates/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属性重命名为文本。为了使过滤工作,您应该搜索与查询参数匹配的名称
根据名称属性进行排序
然后迭代所有结果,每个条目都变成一个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)

最新更新