[英]How to upload text file (specific format) to java script array in flask app?
I have a text file in my static folder that contains a list of specific colleges that I want to use for my autocomplete search in my html page. 我的静态文件夹中有一个文本文件,其中包含要在HTML页面中进行自动完成搜索的特定大学的列表。
This is the format of the text file (college_list.txt): 这是文本文件(college_list.txt)的格式:
["college1", "college2", ... "final college"]
This is my autocomplete function in my layout template: 这是布局模板中的自动完成功能:
<!-- 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)
Let your college_list.txt
be formatted like this: 让您的college_list.txt
格式如下:
College 1
College 2
College 3
.
.
final college
In routes.py
add a new route /colleges
to get the list of colleges as json 在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})
In your layout.html
modify your script to get college list using ajax call 在您的layout.html
修改脚本以使用Ajax调用获取大学列表
<script>
$(function () {
$("#college_search").autocomplete({
source: function (request, response) {
$.ajax({
url: "./colleges",
success: function (data) {
response(data.colleges);
}
});
}
});
});
</script>>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.