Jquery Django-在post后更新基本模板的分区,无需重新加载
我想在我的基本模板中包括通知,因为它位于stackoverflow左上角。我知道这可以通过定制模板标签或定制上下文处理器来实现 现在我的要求是,我不希望每次加载页面时都加载通知,而是只希望在单击通知图标时加载通知 我不知道还需要什么代码或脚本,因为我是jquery/ajax新手 如果需要任何其他细节,请告诉我。谢谢 编辑:(添加以下详细信息) context_prprocessors.py:Jquery Django-在post后更新基本模板的分区,无需重新加载,jquery,ajax,django,Jquery,Ajax,Django,我想在我的基本模板中包括通知,因为它位于stackoverflow左上角。我知道这可以通过定制模板标签或定制上下文处理器来实现 现在我的要求是,我不希望每次加载页面时都加载通知,而是只希望在单击通知图标时加载通知 我不知道还需要什么代码或脚本,因为我是jquery/ajax新手 如果需要任何其他细节,请告诉我。谢谢 编辑:(添加以下详细信息) context_prprocessors.py: def notifications(request): if request.POST and req
def notifications(request):
if request.POST and request.is_ajax:
notify_obj = #some logic here
return {'notify_obj': notify_obj}
base.html(部分):
{%csrf_令牌%}
{notify_obj%}中的notify为%
{{notify.user.user_id.username},{{notify.wish.wish_text}-{{notify.added}
{%endfor%}
$(文档).ready(函数(){
$('#notify form').submit(函数(){//捕获表单的提交事件
$.ajax({//创建一个ajax调用。。。
数据:$(this).serialize(),//获取表单数据
类型:$(this.attr('method'),//GET或POST
url:$(this.attr('action'),//要调用的文件
成功:函数(响应){//on success。。
$('#notify div').html(响应);//更新div
}
});
返回false;
});
});
请告诉我应该在这里使用wht JS。我认为您不应该同时使用post表单、模板标签和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();" />
函数loadNotification(){
$.get(“/url/to/notifications”,函数(数据){
$(“#通知表格”).html(数据);
});
}
另外,我会使用GET请求而不是POST
我希望我足够清楚;-) 我敦促您查看,而不是编写自己的通知应用程序。在必要时将其连接到
$.get()
是很简单的。非常感谢,这真的很有帮助。我走错了路。我对GET和POST感到困惑。再次感谢:)
<script>
function loadNotification() {
$.get( "/url/to/notifications", function( data ) {
$( "#notify-form" ).html( data );
});
}
</script>
<input id="clickMe" type="button" value="clickme" onclick="loadNotification();" />