我想在Flask中创建一个LiveSearch。所以我试过了。我建立了一个到sqlite数据库的连接。在数据库中,我只有四个条目用于测试。如果我启动flask并写入输入字段,例如"P",我只收到一个4x的"Undefinded“,而不是所希望的entrys from the database like "PET","PA6","PE-LT”等等。我坐了几个小时,到处试着找,不知道我做错了什么。希望你能帮我。
以下是我正在使用的代码:search.py
from flask import Flask, render_template, jsonify, request
import sqlite3 as sql
app = Flask(__name__)
@app.route("/")
def index():
return render_template("index.html")
@app.route("/livesearch", methods=["POST", "GET"])
def livesearch():
searchbox = request.form.get("text")
con = sql.connect("DIMOP.db")
cur = con.cursor()
cur.execute("""SELECT Kennwert FROM Materialien WHERE Kennwert LIKE ?""", ('%'+searchbox+'%', ))
result = cur.fetchall()
return jsonify(result)
if __name__ == "__main__":
app.run(debug=True)index.html
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
</head>
<body>
<input type="text" id="livebox">
<p id="datalist"></p>
<script type=text/javascript>
$(document).ready(function(){
$("#livebox").on("input",function(e){
textinlivebox = $("#livebox").val();
$.ajax({
method:"post",
url:"/livesearch",
data:{text:textinlivebox},
success:function(res){
var data = "<ul>";
$.each(res,function(index,value){
data += "<li>"+value.Kennwert+"</li>";
});
data += "</ul>";
$("#datalist").html(data);
}
});
});
});
</script>
</body>
</html>发布于 2021-06-16 06:16:26
我在我的一个项目中使用了类似的东西,它工作得很好。
views.py:
@api.route("/livesearch",methods=["POST"])
def livesearch():
name = request.form.get('name')
data = {"name": name}
return jsonify(data)index.html:没有表单,只是一个输入。
...
<input type="text" id="livebox" class="form-control text-right">
...
$(document).ready(function(){
$("#livebox").on("input",function(e){
if($("#livebox").val().length > 4)
{
$.ajax({
method:"post",
url:"/api/livesearch",
data:{name:$("#livebox").val()},
success:function(res){
if(res != '')
{
console.log(res['name']);
}
else
{
alert('failed');
}
},
});
}
});
});我真正的view.py是这样的,很抱歉我的脏代码,我是一个新手。
@app.route("/livesearch",methods=["POST"])
def livesearch():
searchbox = request.form.get("text")
cursor = mysql.connection.cursor()
query = "select * from books where name LIKE '%{}%' order by name".format(searchbox)
cursor.execute(query)
result = cursor.fetchall()
data = []
for row in result:
if row[2] == 'None':
data.append({'id': row[0], 'name': row[1], 'price':row[4], 'specialprice':row[3], 'img':row[5]})
else:
data.append({'id': row[0], 'name': row[1], 'price':row[2], 'specialprice':'0','img':row[5]})
return jsonify(data)https://stackoverflow.com/questions/62413092
复制相似问题