AJAXリクエストは、開発者(あなた)がそう言ったときに発生します。たとえば、AJAXリクエストを行うために特定のボタンを「クリックする」ことでイベントリスナーを設定した場合、AJAXリクエストが行われます。
で特定のボタンのクリックイベントを「リッスンする」イベントリスナーがあるとします。
{# Place this as a separate html file, say "ajax_comments.html" #}
<div id="my-placeholder">
{% for comment in comments %}
{{ comment }}
{% endfor %}
<button id="my-button">Update comments</button>
</div>
{# END OF PLACE THIS #}
{# ############################################################### #}
{# Begin of your main HTML template, say "my_template.html" #}
....
{% include 'path/to/ajax_comments.html' %}
....
// make an Ajax call (GET request) to the same url, using jQuery.
$(document).ready(function() {
$('#my-button').on('click', function() {
$.ajax({
'method': 'GET', // defaults to GET. Set POST if you like, but be aware of the CSRF token submission too!
'url': '.', // submit to the same url
'data': {}, // pass here any data to the server. You can omit it.
success: function(dataReturned) {
// This function will run when server returns data
$('#my-placeholder').replaceWith(dataReturned);
}
});
});
});
{# END OF "my_template.html" #}
HTML、JSで終了します。今すぐあなたのviews.py
に。
def my_view(request):
if request.is_ajax():
# If you have passed any data through the 'data' property
#you can get it here, according to the method used.
my_data = request.GET.get('data-name')
comments = Comment.objects.filter().order_by('-timestamp')
# Note that we are passing the 'ajax_comments.html' template.
return render(request, 'ajax_comments.html', {'comments': comments})
comments = Comment.objects.filter().order_by('-score__upvotes')
return render(request, 'my_template.html', {'comments': comments})
- ボタンは、AJAXリクエストがあなたの意見の中に、サーバー
- に作られ、あなたが要求のこの種を扱う、あなたが新しいとHTML部分を返す
- テンプレートに押されクエリーセット。
- このリターンはテンプレートに直接レンダリングされませんが、これを待っている関数
$.ajax()
に行きます。
- 一度受け取った、それは(新しいものに
div
のデータを交換する)私たちがやって書いたものを行い
希望これはあなたを助けます!
返信いただきありがとうございます。私はあなたに非常に似たようなコードを使ってクエリーセットを変更することができましたが、何らかの理由で、新たにロードされた子テンプレートでJavaScriptが動作していません。理由は何ですか?私はここに質問をしました:http://stackoverflow.com/questions/42126427/js-stops-working-on-child-template-when-i-perform-an-ajax-call-to-change-the- que?noredirect = 1#comment71422842_42126427 – Zorgan