我想实现一个简单的搜索功能,当用户在框中输入文本时,它将通过json file [large.js]以查看是否有任何匹配的记录。如果是,将显示结果。
问题是当我运行py文件时,出现错误No such file or directory "large"
任何想法都会很棒。谢谢
下面是python代码[application.py]
from flask import Flask, render_template, request, jsonify
app = Flask(__name__)
WORDS = []
with open("large", "r") as file:
for line in file.readlines():
WORDS.append(line.rstrip())
@app.route("/")
def index():
return render_template("index.html")
@app.route("/search")
def search():
q = request.args.get("q")
words = [word for word in WORDS if word.startswith(q)]
return jsonify(words)
Run Code Online (Sandbox Code Playgroud)
下面是 HTML 代码 [templates/index.html]
<input type="text">
<ul></ul>
<script src ="large.js"></script>
<script>
let input = document.querySelector("input")
input.onkeyup = function (){
let html = "";
if (input.value){
for (word of WORDS){
if (word.startsWith(input.value)){
html += "<li>" + word +"</li>";
}} }
document.querySelector("ul").innerHTML = html;
};
</script>
Run Code Online (Sandbox Code Playgroud)
包含 json 的large.js 文件
let WORDS = [
"a",
"abandon",
"abandoned",
"ability",
"able"]
Run Code Online (Sandbox Code Playgroud)
创建一个名为 的文件夹static,然后在该static文件夹内创建另一个名为 的文件夹js并将large.js文件放入其中
在你templates/index.html把这个改成
<script src ="large.js"></script>
这个
<script src ="{{ url_for('static', filename='js/large.js') }}"></script>
之后您的应用程序结构应该类似于
然后在您的代码中尝试类似下面的内容,让我知道会发生什么
import os
from flask import Flask, render_template, request, jsonify
basedir = os.path.abspath(os.path.dirname(__file__))
data_file = os.path.join(basedir, 'static/js/large.js')
WORDS = []
with open(data_file, "r") as file:
for line in file.readlines():
WORDS.append(line.rstrip())
app = Flask(__name__)
@app.route("/")
def index():
return render_template("index.html")
@app.route("/search")
def search():
q = request.args.get("q")
words = [word for word in WORDS if word.startswith(q)]
return jsonify(words)
Run Code Online (Sandbox Code Playgroud)