简体   繁体   中英

How would I pass a JavaScript parameter into my python code in flask?

<script type="text/javascript">
      function reply_click(clicked_id)
      {
        document.getElementById("viewFlashcardLabel").innerHTML = '{{ flashcards.query.filter_by(id = clicked_id).first().title }}';   
      }
</script>

The parameter clicked_id is not being recognised by the python code in the {{ }}. What would be an easy and secure way to fix the bug?

Edit:

HTML file:

    <script>
      function getFlashcard(id)
      {
        $.ajax({
          type: 'POST',
          url: "{{ url_for('views.get_flashcard') }}",
          data: {"id" : 1},
          success: function(){
            alert("success")
          },
          error: function(){
            alert("error")
          }
        });
        e.preventDefault();
      }
      
    </script>

Python file:

@views.route('/get_flashcard', methods=['GET', 'POST'])
@login_required
def get_flashcard():
    if request.method == 'POST':
        print("recieved request")

The problem is that my ajax call is not being received by my python code as my test message is not being printed.

You are not able to do that with jinja template alone.

Add a new API, its url is something like /api/get_title_by_id . It can query the title by id parameter.

In you your javascript code, make an ajax call to the new API to get the title.

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