首页 > 解决方案 > 如何将文本文件(特定格式)上传到烧瓶应用程序中的 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)

标签: javascriptpythonarraysflask

解决方案


让您的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>>

推荐阅读