[英]Avoid 405 errors using AJAX with Flask + JINJA
請謹慎,因為我剛開始從事后端工作,但已進行搜索以尋找答案。
我正在創建一個應用程序,該應用程序返回從第三方API檢索到的搜索結果。
我正在實現對該API的另一個調用,以檢索有關單個結果的更多信息,並且我想通過AJAX進行操作。
這是我的JINJA2模板代碼。 我正在嘗試獲取一個id,並將其傳遞給我的flask函數,該函數返回結果並填充關聯的div。 在服務器上,我收到405響應。
{% 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 %}
這是我接受json並返回結果的簡單函數(我構建了一個單獨的函數來調出API,未顯示)。
@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)
問題很清楚,您的路由僅允許POST方法,但是您使用的是$.getJSON
,如果您想使用POST方法,則它是GET方法
試試$ .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)
或者,如果您想使用GET方法
嘗試這個
@app.route('/list_comments', methods=['GET'])
@login_required
def listComments():
a = request.args.get('a', 0, type=int)
comments = getComments(a)
return jsonify(comments)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.