Frage

Please be gentle, as I'm newish to backend work, but have searched to try to find the answer.

I'm creating an application that returns search results retrieved from a 3rd party API.

I am implementing another call to that API to retrieve more information about an individual result, and I want to do it via AJAX.

Here is my JINJA2 template code. I'm trying to grab an id, pass it to my flask function, which returns the results and populate the associated div. On the server, I get a 405 response.

{% extends "layout.html" %}
{% block body %}
<script type=text/javascript>
  $(function() {
    $("a#listComments").bind('click', function() {
        $.getJSON('list_comments', {
            a: $('li[id="id"]').val()
        }, function(data) {
            $("#comments").text(data.result);
        });
    console.log("This actually worked");
     });
  });
</script>
  <form>
  <ul class=table>
  {% for result in results %}
    <li id="id">{{ result.id }}</li>
    <p>{{ result.title }}</p>
    <p><a href="javascript:void();" id="listComments">List Comments</a>
    <span id="comments">?</span>
  {% else %}
    <li><em>Unbelievable, no results</em>
  {% endfor %}
  </ul>
  </form>
{% endblock %}

Here is my simple function to accept the json and return the results (which I built a separate function to call out to the API, not shown).

@app.route('/list_comments', methods=['POST'])
def listComments():
    if not session.get('logged_in'):
        abort(401)
    if request.method == 'POST':
        #a = request.args.get('a', 0, type=int)
        comments = getComments(a)
        return jsonify(comments)
War es hilfreich?

Lösung

Problem is very clear your route allowed only POST method but you are using $.getJSON it is a GET method if you want to use POST method

Try $.post

$.post('/list_comments', { 
              a: $('li[id="id"]').val()
          }, function(data) {
          //data contains the JSON object
}, "json");

@app.route('/list_comments', methods=['POST'])
@login_required
def listComments():
    a = request.form.get('a')
    comments = getComments(a)
    return jsonify(comments)

OR if you want to use GET method

Try this

@app.route('/list_comments', methods=['GET'])
@login_required
def listComments():
    a = request.args.get('a', 0, type=int)
    comments = getComments(a)
    return jsonify(comments)
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top