Change a variable without reloading the page

I have a list of image names loaded with a flask that I pass to the html template so that the page displays the image. The only way to change the list of images (i.e. add an image to it) is to make a view containing the code to change the list, but to access the view you need to reload the entire page again. Is there a way to change a list with a jar without reloading the entire page?

+4
source share
1 answer

Jacob Boyer is absolutely right - use 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 click 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> 
+10
source

Source: https://habr.com/ru/post/1443274/


All Articles