简体   繁体   中英

How to use AJAX in Flask to iterate through a list

Problem

I am trying to display image-files using AJAX in Flask. More specifically, I want to display an image once a button is clicked and display the next image once the button is clicked again (like a slide-show). The filenames of the images are stored in my database. I query the database to get a list of filenames for the current user and combine each filename with the rest of the path (path to where the images are stored on disk) in order to display the image.

So far, I manage to get the first image of the current user. However, I can't figure out a way to keep track of which image is the next one to show.

I tried using a global variable as a counter ( file_counter ) which should serve as an index. I want to increase file_counter by 1 each time an ajax request is made in order to get the next file but the counter does not increase upon subsequent calls nor does it throw an error.

Question

How do I need to initialize the global variable (file_counter) in order for it to store its value across multiple calls? Furthermore, is the usage of global variables the correct way of doing this?

HTML

<div id="ajax-field"></div>
<button class="btn btn-block"  id="next-button"><p>Next Image!</p></button>

AJAX:

$('#next-button').click(function(){
         $("#ajax-field").text("");
         $.ajax({
                        url: "/get_data",
                        type: "POST",
                        success: function(resp){
                            $('#ajax-field').append(resp.data);
                        }
                    });
                        });

Routing:

global filenames
global file_count
@app.route("/get_data", methods=['POST'])
def get_data():
    try: # Is intended to fail on the first run in order for the global variables to be initialized. However it keeps failing on subsequent runs
        display_img = filenames[file_count]
        file_count +=1
    except:

        filenames = []
        # current_user.uploads returns all file-objects of the current user
        user_uploads = current_user.uploads
        for file in user_uploads:
            # file.filename returns the respective filename of the image
            filenames.append(file.filename)
        #filenames is now a list of filenames i.e. ['a.jpg','b.jpg','c.jpg'...]
        display_img = filenames[0]
        file_count = 1

    path = "image_uploads/4_files/"+display_img

    return jsonify({'data': render_template('ajax_template.html', mylist = path)})

ajax_template.html:

<ul>
{% block content %}
    <li>
        <img id="selected-image-ajax" src="{{url_for('static',filename=mylist)}}"  class="img-thumbnail" style="display:block; margin:auto;"></img>
    </li>
{% endblock content %}
</ul>

As @roganjosh pointed out, a session is the optimal way to store information across multiple requests. This solution presents an implementation of the photo display using flask.session to store the counter:

import flask, random, string
app = flask.Flask(__name__)
app.secret_key = ''.join(random.choice(string.printable) for _ in range(20))
#to use flask.session, a secret key must be passed to the app instance

@app.route('/display_page', methods=['GET'])
def display_page():
  '''function to return the HTML page to display the images'''
  flask.session['count'] = 0
  _files = [i.filename for i in current_user.uploads]
  return flask.render_template('photo_display.html', photo = _files[0])

@app.route('/get_photo', methods=['GET'])
def get_photo():
   _direction = flask.request.args.get('direction')
   flask.session['count'] = flask.session['count'] + (1 if _direction == 'f' else - 1)
   _files = [i.filename for i in current_user.uploads]
   return flask.jsonify({'photo':_files[flask.session['count']], 'forward':str(flask.session['count']+1 < len(_files)), 'back':str(bool(flask.session['count']))})

The display_page function will be called when a user accesses the /display_page route and will set the count to 0 . get_photo is bound to the /get_photo route and will be called when the ajax request is sent.

photo_display.html :

<html> 
  <head>
   <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
   </head>
   <body>
      <div class='image_display'>
        <img src="{{photo}}" id='photo_display' height="100" width="100">
        <table>
         <tr>
           <td class='back'></td>
           <td class='forward'><button id='go_forward' class='navigate'>Forward</button></td>
         </tr>
        </table>
      </div>
   </body>
   <script>
    $(document).ready(function(){
      $('.image_display').on('click', '.navigate', function(){
        var direction = 'b';
        if ($(this).prop('id') === 'go_forward'){
          direction = 'f';
        }

        $.ajax({
         url: "/get_photo",
         type: "get",
         data: {direction: direction},
         success: function(response) {
           $('#photo_display').attr('src', response.photo);
           if (response.back === "True"){
             $('.back').html("<button id='go_back' class='navigate'>Back</button>")
           }
           else{
             $('#go_back').remove();
           }
           if (response.forward === "True"){
             $('.forward').html("<button id='go_forward' class='navigate'>Forward</button>")
           }
           else{
             $('#go_forward').remove();
           }

         },

       });
      });
    });
   </script>
</html>

The javascript in display_page.html communicates with the backend, and updates the img tag src accordingly. The script adds or removes the navigation buttons, depending on the current count value.


Demo:

To test the solution above, I created an image folder to store random photographs to display:

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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