2013-11-26 21 views
0

我想在我的基本模板中包含通知,因爲它在stackoverflow左上角。我知道這可以通過製作自定義模板標籤或自定義上下文處理器來完成。Django在發佈後無需重新加載基本模板的更新部分

現在我的要求是,我不希望每次加載頁面時都加載通知,而只是當我們點擊通知圖標時才加載通知。

我不知道其他代碼或腳本是必需的,因爲我是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要我在這裏使用。

回答

1

我認爲,如果您的通知來自兩種方式(模板視圖和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。

我希望我足夠清楚;-)

+0

非常感謝,這真的有幫助。我錯誤地採取了錯誤的做法。我很困惑與GET和POST。再次感謝 :) –

0

我勸你看看Django messages framework,而不是寫自己的通知應用程序。在必要時將它掛接到$.get()是微不足道的。

相關問題