0
我的计划是创建一个网站,人们可以在其中写日记并阅读他人的日记,而我目前正在实施搜索框,用户可以搜索用户名阅读其他人的日记(例如,如何在Facebook上查找朋友),所以我为搜索框编写了以下代码,使用Python代码(包含SQLite语句)从数据库中提取搜索结果并使用JavaScript不断执行搜索动作,输出到search.html
作为动态下拉菜单。但是,下拉部分不起作用。HTML下拉菜单/ Typeaheads(从Python到JavaScript)
Application.py
@app.route("/search", methods=["GET", "POST"])
@login_required
def search():
"""Search published diaries from others."""
# if user reached route via POST (as by submitting a form via POST)
if request.method == "POST":
# ensure friends' usernames were submitted
if not request.form.get("search"):
return dumbo("No username entered")
# search user's friends from database
# append % to q so that user doesn't have to input city/state/postal code in the URL completely/accurately
# https://www.tutorialspoint.com/sqlite/sqlite_like_clause.htm
friend = request.form.get("search") + "%"
searches = db.execute("SELECT username FROM writers WHERE username LIKE :friend", friend=friend)
# output a JSON array of objects, each represents a row from TABLE writers that matches what the user looks for
return jsonify(searches)
# else if user reached route via GET (as by clicking a link or via redirect)
else:
return render_template("search.html")
scripts.js中
$("#friend").keydown(function() {
// configure typeahead
$("#friend").typeahead({
// If true, when suggestions are rendered, pattern matches for the current query in text nodes
// will be wrapped in a strong element with its class set to {{classNames.highlight}}. Defaults to false.
highlight: false,
// The minimum character length needed before suggestions start getting rendered. Defaults to 1.
minLength: 1
},
{
display: function(suggestion) { return null; },
limit: 5,
source: search,
templates: {
suggestion: Handlebars.compile(
"<div>" +
"<div>{{username}}</div>" +
"</div>"
)
}
});
// action after friend is selected from drop-down
$("#friend").on("typeahead:selected", function(eventObject, suggestion, name) {
// visit friend's diaries (to be continued)
});
});
/**
* Searches database for typeahead's suggestions.
*/
// search calls asyncResults after searching is done (asynchronously)
function search(query, syncResults, asyncResults)
{
// get usernames matching query (asynchronously)
var parameters = {
friend: $("#friend").val()
};
$.getJSON(Flask.url_for("search"), parameters)
.done(function(data, textStatus, jqXHR) {
// call typeahead's callback with search results (i.e., friends)
asyncResults(data);
})
.fail(function(jqXHR, textStatus, errorThrown) {
// log error to browser's console
console.log(errorThrown.toString());
// call typeahead's callback with no results
asyncResults([]);
});
}
search.html
{% extends "layout.html" %}
{% block title %}
Search
{% endblock %}
{% block main %}
<form action="{{ url_for('search') }}" method="post">
<fieldset>
<div class="form-group">
<input autocomplete="off" autofocus class="typeahead" id="friend" name="search" placeholder="Search friends" type="text"/>
</div>
<div class="form-group">
<button class="btn btn-default" type="submit">Search</button>
</div>
<!-- https://www.mkyong.com/javascript/how-to-link-an-external-javascript-file/ -->
<script type="text/javascript" src="static/scripts.js"></script>
</fieldset>
</form>
{% endblock %}
我从字面上刚刚开始学习CS,所以请告知,如果我是一个白痴, 谢谢!!!!
我改成了'$ .post'但在下拉菜单中仍然没有“在下降”选项...任何更多的建议吗? @leaf –
使用'print'在服务器端记录'request.form'.It似乎当typeahead调用'search'时,它没有来自'parameters'的合适表单字段 – leaf
我将'return jsonify(searches)'改为'打印(搜索)',但未能解决问题。请指教,谢谢! @leaf –