[英]Django- update division of base template after post without reload
我想在基本模板中包含通知,因為它在stackoverflow左上角。 我知道可以通過制作自定義模板標簽或自定義上下文處理器來完成 。
現在,我的要求是,我不想每次加載頁面時都加載通知,而只想單擊通知圖標時才加載通知。
我不知道還需要什么其他代碼或腳本,因為我是jquery / ajax的新手。
如果需要其他詳細信息,請告訴我。 謝謝。
編輯:(添加以下詳細信息)
context_prrocessors.py:
def notifications(request):
if request.POST and request.is_ajax:
notify_obj = #some logic here
return {'notify_obj': notify_obj}
base.html(部分):
<div id="notify-div">
<form id="notify-form" method="post">
<input type="submit" name="notify" value="Show notifications">
{% csrf_token %}
</form>
{% for notify in notify_obj %}
{{ notify.user.user_id.username }}, {{ notify.wish.wish_text }} - {{ notify.added }}
{% endfor %}
</div>
<script>
$(document).ready(function() {
$('#notify-form').submit(function() { // catch the form's submit event
$.ajax({ // create an AJAX call...
data: $(this).serialize(), // get the form data
type: $(this).attr('method'), // GET or POST
url: $(this).attr('action'), // the file to call
success: function(response) { // on success..
$('#notify-div').html(response); // update the DIV
}
});
return false;
});
});
</script>
請告訴我我應該在這里使用JS。
我認為您不應該將帖子表單,模板標簽和Ajax同時使用,除非您的通知來自兩種方式(模板視圖和Ajax)。 如果我是你,我將只使用Ajax + javascript做所有事情。
僅用在“ onclick”屬性中包含函數的按鈕替換表單,該按鈕將對通知視圖進行Ajax調用,然后使用成功回調更新div標簽。
<script>
function loadNotification() {
$.get( "/url/to/notifications", function( data ) {
$( "#notify-form" ).html( data );
});
}
</script>
<input id="clickMe" type="button" value="clickme" onclick="loadNotification();" />
另外,我將使用GET請求而不是POST。
我希望我足夠清楚;-)
我敦促您查看Django消息框架 ,而不要編寫自己的通知應用程序。 在必要時將其連接到$.get()
很簡單。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.