jQuery Создать форму автозаполнения - PullRequest
0 голосов
/ 22 декабря 2018

Мне нужна ваша помощь с моей формой поиска в Adjust.html.Он должен получить данные от пользователя "q" и предложить возможные записи из таблицы базы данных "book" [book table.Пользователь должен выбрать одно из предложений и нажать кнопку «Добавить».

При запуске программы появляется следующая ошибка: «RuntimeError: Missing input». Error message I'mблагодарен за ваши идеи и исправления.

Вот мои коды JavaScript, Python и HTML:

function configure()
    {
    // Configure typeahead
    $("#q").typeahead({
        highlight: false,
        minLength: 1
    },
    {
        display: function(suggestion) { return null; },
        limit: 10,
        source: search,
        templates: {
            suggestion: Handlebars.compile(
                "<div>"+
                "{{Title}}, {{Author}}" +
                "</div>"
            )
       },
        updater: function(item) {
        //take selected item and submit to the form
        this.$element[0].value = item;
        this.$element[0].form.submit();
        return item;
        }
    });
    // Hide info window when text box has focus
    $("#q").focus(function(eventData) {
        info.close();
    });

    // Give focus to text box
    $("#q").focus();
}

// Search database for typeahead's suggestions
function search(query, syncResults, asyncResults)
{
    // Get places matching query (asynchronously)
    let parameters = {
        q: query
    };
    $.getJSON("/adjust", parameters, function(data, textStatus, jqXHR) {

        // Call typeahead's callback with search results (Author Title)
        asyncResults(data);
    });
}

Код Python:

@app.route("/adjust", methods=["GET", "POST"])
@login_required
def search():
    """Search for books that match query"""
    if request.method == "GET":
        if not request.args.get("q"):
            return render_template("adjust.html")
        else:
            if request.args.get("q"): # handle ajax request
                q = request.args.get("q")  + "%"
            else:
                q = request.args.get("q")  + "%" # handle form submit

            books = db.execute("SELECT Title, Author FROM book WHERE Title LIKE :q OR Author LIKE :q", q=q)
    return jsonify(books)

HTML-код:

{% extends "layout.html" %}
{% block title %}
    Add your Book
{% endblock %}
{% block main %}
    <form action="/adjust">
        <div class="form-group">
        <p>Choose your Book</p>
        <label class="sr-only" for="q">Title, Author</label>
        <input class="form-control" id="q" placeholder="Title, Author" type="text"/>
        </div>
        <button class="btn" type="submit">Add</button>
    </form>
{% endblock %}

1 Ответ

0 голосов
/ 24 декабря 2018

Ошибка не из Javascript, а из-за фляги, которая не может отобразить adjust.html для sql токена, неверна, это не ...LIKE: q, а ...LIKE :q

и здесь исправлен код

@app.route("/adjust", methods=["GET", "POST"])
@login_required
def search():
    """Search for books that match query"""
    if request.method == "GET":
        if not request.args.get("q"):
            return render_template("adjust.html")
        else:
            if request.args.get("q"): # handle ajax request
                q = request.args.get("q")  + "%"
            else:
                q = request.form.get("q") + "%" # handle form submit

            books = db.execute("SELECT Title, Author FROM book WHERE Title LIKE :q OR Author LIKE :q", q=q)
    return jsonify(books)
...