[英]How to upload text file (specific format) to java script array in flask app?
我的靜態文件夾中有一個文本文件,其中包含要在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>>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.