【问题标题】:Send file path from flask to Ajax将文件路径从烧瓶发送到 Ajax
【发布时间】:2021-01-30 15:07:29
【问题描述】:

我正在尝试向我的 Ajax 脚本发送文件路径,该脚本读取文件内容并将其显示在页面上

@app.route('/main', methods=['GET'])
def main():
    filename = '/static/js/'+current_user.username+'log.txt'
    return render_template('main.html',name=current_user.username,data=filename)

js 脚本

var checkInterval = 1; //seconds
var fileServer = '{{ data }}';
var lastData;

function checkFile() {
    $.get(fileServer, function (data) {

        if (lastData !== data) {
            $( "#target" ).val( data );
            $( "#target" ).animate({
                scrollTop: $( "#target" )[0].scrollHeight - $( "#target" ).height()
            }, 'slow');
            lastData = data;
        }
    });
}

$(document).ready(function () {
    setInterval(checkFile, 1000 * checkInterval);
});

我尝试了不同的方法来做到这一点,将 fileServer 更改为 'data.filename'/{{ data| json }} 等但没有运气。 我该怎么做?

【问题讨论】:

    标签: python html ajax flask


    【解决方案1】:

    如果您将使用 url_for 生成的整个 url 作为参数传递它应该可以工作。

    @app.route('/main', methods=['GET'])
    def main():
        filename = url_for('static', filename=f'js/{current_user.username}log.txt')
        return render_template('main.html', name=current_user.username, data=filename)
    

    作为补充,我还指定请求不应该存储在缓存中。

    const checkInterval = 1;
    const fileServer = "{{ data }}";
    let lastData;
    
    function checkFile() {
      $.get({ url: fileServer, cache: false }, function(data) {
        if (lastData !== data) {
          $("#target").val(data);
          $("#target").animate({
            scrollTop: $("#target")[0].scrollHeight - $("#target").height()
          }, "slow");
          lastData = data;
        }
      });
    }
    
    $(document).ready(function() {
      setInterval(checkFile, 1000 * checkInterval);
    });
    

    我使用 jquery 版本 3 进行测试。

    【讨论】:

    • 对我不起作用。在控制台中得到了这个` jquery-3.3.1.js:9600 GET 127.0.0.1:5002/%7B%7B%20data%20%7D%7D 404 (NOT FOUND)`
    • @Goroshek 好像 jinja 没有传递变量或没有转换 {{data}} 语句。我现在无法解释自己。
    • @Goroshek 它现在对我有用f'/static/js/{current_user.username}log.txt' 和没有url_for。但你现在的问题不同了。
    • @Goroshek 抱歉,我无法重现该错误,也不知道为什么会发生。
    • @Goroshek 抱歉,我不认为您可以将代码拆分为多个文件。声明 {{data}} 仅在 jinja2 模板中有效,在外部 javascript 文件中无效。将 url 作为参数传递是一种解决方案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-03
    • 2018-04-05
    • 2019-05-13
    • 2017-10-15
    • 1970-01-01
    相关资源
    最近更新 更多