javascript - 如何将文本文件(特定格式)上传到烧瓶应用程序中的 java 脚本数组?
问题描述
我的静态文件夹中有一个文本文件,其中包含我想在我的 html 页面中用于自动完成搜索的特定大学列表。
这是文本文件 (college_list.txt) 的格式:
["college1", "college2", ... "final college"]
这是我的布局模板中的自动完成功能:
<!-- Autocomplete JS -->
<link href = "https://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css" rel = "stylesheet">
<script src = "https://code.jquery.com/jquery-1.10.2.js"></script>
<script src = "https://code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
<script>
$(function() {
var collegeList = [
UPLOADED LIST HERE!!!!
];
$( "#college_search" ).autocomplete({
source: collegeList
});
});
</script>
- routes.py
- models.py
- forms.py
- static
- college_list.txt
-templates
- layout.html (where I want to upload the college_list into autocomplete function)
解决方案
让您的college_list.txt
格式如下:
College 1
College 2
College 3
.
.
final college
在routes.py
添加一条新路线/colleges
以将大学列表获取为 json
from flask import Flask, jsonify
...
import os
@app.route('/colleges')
def get_college_list():
with open(os.path.join(app.root_path, 'static', 'college_list.txt'), "r") as f:
colleges = [college.rstrip() for college in f.readlines()]
return jsonify({"colleges" : colleges})
在您layout.html
修改脚本以使用 ajax 调用获取大学列表
<script>
$(function () {
$("#college_search").autocomplete({
source: function (request, response) {
$.ajax({
url: "./colleges",
success: function (data) {
response(data.colleges);
}
});
}
});
});
</script>>
推荐阅读
- c++ - XDP 和 eBPF 性能与 AMD EPYC CPU
- java - Apache Flink Process xml并将它们写入数据库
- python - 如何处理带有字符串循环的空格?
- java - 如何通过 netbeans 设计 UI 编辑自动生成的代码?
- javascript - 如何在 ReactJS 中的 2 个类之间传递数据
- python - 带错误报告的二进制到十进制计算器
- javascript - 在 Jest/Testing Library 测试套件中意外的 afterAll 执行
- oauth-2.0 - 如何使用用户 Api 密钥调用 youtube Api
- django - 如何在 Django/Mysql 中建立一对多关系?
- android - 我们是否开始在本地为 firebase 编写云函数?