【问题标题】:JQuery to reload DIV? (Flask/Jinja2)jQuery重新加载DIV? (烧瓶/Jinja2)
【发布时间】:2017-03-12 11:23:47
【问题描述】:

我搜索无济于事。我想我的问题有点独特。我有一个包含一些内容的 DIV,当前通过将 SQL 查询的对象传递到模板中来引入该内容。这很好用,但不允许我每 x 秒更新一次内容,而不刷新整个页面。我不想做的事情。所以我想知道我可以强制 JQuery 重新加载我的 DIV 元素吗?这还会重新加载其中的代码吗?因为那会迫使我的 div 更新。这是代码。

<div id=content1>
    {{ set content = get_content(parm1, parm2) }} # This is a custom Jinja2 function I wrote to pull the content I need one in the template, but it only runs once.
    {% for row in content %}
    .. do stuff
    {% endfor %}
</div>

是否有可能让 JQuery 使用已经存在的代码重新加载该 DIV?如果是这样,那应该可以解决我的问题。我曾考虑尝试创建一个调用以获取 JSON 中的内容,但如果可能的话,我宁愿不这样做。

【问题讨论】:

    标签: javascript jquery python flask jinja2


    【解决方案1】:

    app.py

    @app.route('/')
    def some_view():
        name = request.args.get('name', 'Anonymous')
        if request.is_xhr:
            template_name = 'template_ajax.html'
        else:
            template_name = 'template.html'
        return render_template(template_name, name=name)
    

    template.html

    <html>
        <head>
            <title>Test</title>
            <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
        <head>
        <body>
            <h3>Title</h3>
            <div>Hello, {{ name }}!</div>
            <p>Some text</p>
    
            <script>
                $(document).ready(function() {
                    $('div').load('/?name=username');
                });        
            </script>
        </body>
    </html>
    

    template_ajax.html

    Hello from AJAX, {{ name }}!
    

    【讨论】:

    • 这就是我最终的结果.. 但有点不同.. 我的问题是.. 你只有 $('div').load();那会只加载当前 DIV 中的内容吗?
    • 是的,$('div').load(); 在 div 中加载内容而不重新加载页面的其余部分。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-22
    • 2022-10-15
    • 1970-01-01
    • 2018-04-16
    • 1970-01-01
    相关资源
    最近更新 更多