简体   繁体   English

在不重新加载页面的情况下更改变量

[英]Changing a variable without reloading the page

I have a list of image names loaded with flask, which I am rendering to an html template, so that the page displays the image. 我有一个装有flask的图像名称列表,我将其渲染为html模板,以便页面显示图像。 The only way I can seem to alter the image list (ie. add an image to it) is to make a view which contains code to change the list, but in order to access the view you have to reload the whole page again. 我似乎可以改变图像列表(即向其添加图像)的唯一方法是创建一个包含更改列表的代码的视图,但是为了访问视图,您必须重新加载整个页面。 Is there any way I can alter the list with flask without having to reload the whole page? 有没有办法我可以用烧瓶更改列表而无需重新加载整个页面?

Jakob Bowyer is absolutely correct - use ajax: Jakob Bowyer绝对正确 - 使用ajax:

from flask import jsonify
from werkzeug.security import safe_join

@app.route("/gallery")
def gallery():
    images = get_images_from_dir("some/base/path/*.jpg")
    return render_template("gallery.html", images=images)


@app.route("/search/images", methods=["POST"])
def search_images():
    glob_path = request.form["image_query"]
    glob_path = safe_join("/some/base/path", glob_path)
    return jsonify(images=get_images_from_dir(glob_path))

Then in your template just hit the appropriate endpoint: 然后在您的模板中点击相应的端点:

<!-- snip -->
<script>
// jQuery here - you can use anything you want :-)
$.post({
    url: "{{ url_for("search_images") }}",
    success: function(data) {
        console.log(data);
    },
    error: function() { console.log("Error", arguments); }
});
</script>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM