【问题标题】:How to upload text file (specific format) to java script array in flask app?如何将文本文件(特定格式)上传到烧瓶应用程序中的 java 脚本数组?
【发布时间】:2019-07-26 01:50:45
【问题描述】:

我的静态文件夹中有一个文本文件,其中包含我想在我的 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)

【问题讨论】:

    标签: javascript python arrays flask


    【解决方案1】:

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

    【讨论】:

    • 添加您的建议后,我现在在尝试从终端 @waynetech 运行烧瓶应用程序时收到错误“simplejson.errors.JSONDecodeError: Expecting value: line 1 column 1 (char 0)”跨度>
    • 您是否重新格式化了您的college_list.txt,如图所示?我们在数组中使用的每个大学名称都在一个新行中,不带引号 (") 和括号 []
    • 是的,我有,我什至创建了一个较小的文本文件列表来测试它,但它仍然不起作用。
    • print(colleges) 就在您的路线中的return jsonify({"colleges" : colleges}) 之前并检查您的日志,您得到了什么结果?发布打印输出,它将在发生错误的位置上方(回溯之前)。您还可以将return 更改为return jsonify({"colleges" : 0}) 以避免错误并检查打印输出
    • 我看到了问题,我也在使用 forms.py 中的文本文件,我只需要用新格式更新它。谢谢!
    猜你喜欢
    • 1970-01-01
    • 2015-07-24
    • 2020-08-30
    • 1970-01-01
    • 1970-01-01
    • 2019-07-11
    • 2021-07-03
    • 2020-06-16
    • 2017-12-03
    相关资源
    最近更新 更多