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.
This is the format of the text file (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 1
College 2
College 3
.
.
final college
In routes.py
add a new route /colleges
to get the list of colleges as 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
<script>
$(function () {
$("#college_search").autocomplete({
source: function (request, response) {
$.ajax({
url: "./colleges",
success: function (data) {
response(data.colleges);
}
});
}
});
});
</script>>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.