正在传递尚未提交给python的html搜索框字符串
我有一个html搜索框。 如果用户点击他们的键盘,我想传递这个尚未提交给python的变量。 我不知道该怎么办。 第一个代码是html搜索框部分,第二个代码是python代码正在传递尚未提交给python的html搜索框字符串,python,html,flask,Python,Html,Flask,我有一个html搜索框。 如果用户点击他们的键盘,我想传递这个尚未提交给python的变量。 我不知道该怎么办。 第一个代码是html搜索框部分,第二个代码是python代码 <br> <input name="Country" type="text" id="Country" placeholder="Enter Country" oninput="myFunction()"/
<br> <input name="Country" type="text" id="Country" placeholder="Enter Country" oninput="myFunction()"/> oninput: <span id="result"></span>
<script>
function myFunction() {
// result.innerHTML = Country.value;
result.innerHTML = output;
};
</script>
是否有任何方法可以传递尚未提交给python的html搜索框字符串?
如果您有任何帮助,我们将不胜感激。这是一个使用AJAX而不提交表单的简单示例 表单字段中的每次更改都会在后台向服务器发送请求。然后,将收到的数据添加到分配给表单字段的数据列表中
@app.route('/')
def index():
return render_template('index.html')
@app.route('/complete')
def complete():
countries = ['China', 'India', 'USA']
country = request.args.get('country', '')
results = [x for x in countries if x.startswith(country)]
return jsonify(results=results)
(功能(){
让countryField=document.querySelector(“输入[name='country']”);
countryField.addEventListener('input',函数(事件){
fetch(`/complete?country=${encodeURIComponent(countryField.value)}`)
.then(resp=>resp.json())
。然后(数据=>{
const dataList=document.getElementById(“国家”);
dataList.innerHTML=“”;
const results=data.results;
results.forEach(项目=>{
让elem=document.createElement(“选项”);
元素setAttribute(“值”,项);
dataList.appendChild(elem);
});
})
.catch(err=>console.error(“error:,err));
},假);
})();
代码当然可以改进,但它说明了在不重新加载页面或最终发送表单的情况下动态获取数据的可能性。为了使您的工作更轻松,我建议使用jQuery之类的库。您是否使用python flask托管网页?如果您正在托管一个网页,您需要从您的文档向该网页发出POST请求。是的,我是。您在这里看到任何问题country=request.form[country.value]吗?您可以通过字段名称请求表单字段的数据。所以表达式应该是
country=request.form['country']
。但是,我认为您需要使用ajaxget请求来获取自动完成所需的数据。因此,页面不会被重新加载,而是异步传输数据,然后将数据集成到page.country=request.form['country']中。我认为这是用户提交时才使用的。我试图在用户提交变量之前传递它
@app.route('/')
def index():
return render_template('index.html')
@app.route('/complete')
def complete():
countries = ['China', 'India', 'USA']
country = request.args.get('country', '')
results = [x for x in countries if x.startswith(country)]
return jsonify(results=results)
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<form>
<input type="text" name="country" list="countries" placeholder="Enter Country" />
<datalist id="countries"></datalist>
</form>
<script type="text/javascript">
(function() {
let countryField = document.querySelector("input[name='country']");
countryField.addEventListener('input', function(event) {
fetch(`/complete?country=${encodeURIComponent(countryField.value)}`)
.then(resp => resp.json())
.then(data => {
const dataList = document.getElementById("countries");
dataList.innerHTML = "";
const results = data.results;
results.forEach(item => {
let elem = document.createElement("option");
elem.setAttribute("value", item);
dataList.appendChild(elem);
});
})
.catch(err => console.error("Error:", err));
}, false);
})();
</script>
</body>
</html>