LiveSearch和Ajax返回未定义的

2024-06-11 13:54:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我想在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>

Tags: text数据库appflaskdataindexhtmlscript
1条回答
网友
1楼 · 发布于 2024-06-11 13:54:45

我在我的一个项目中使用了类似的东西,效果很好

views.py:

@api.route("/livesearch",methods=["POST"])
def livesearch():
    name = request.form.get('name')
    data = {"name": name}
    return jsonify(data)

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

我真正的视图.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)

相关问题 更多 >