我想在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>
我在我的一个项目中使用了类似的东西,效果很好
views.py:
html:没有表单,只是一个输入
我真正的视图.py是这样的,对不起,我的代码太脏了,我是个新手
相关问题 更多 >
编程相关推荐