精简版:
ajax 调用后,链接变为纯文本,但在页面刷新时返回链接。
细节:
我有一个通知系统(如 Stack Overflow 等)。通知位于下拉子模板中:
notification_menu_list.html
{% 加载 display_tags %} {% 加载 item_tags %}
<div id='notification_header'>{{ request.user|count_unread_notifications }} notification{{ request.user|count_unread_notifications|pluralize}}</div>
<ul id='notification_box'>
{% for notification in request.user|get_notifications|slice:"6" %}
{% if notification.active %}
<li class='unread notification' id='{{notification.pk}}'>{{notification.headline|safe}}</li>
{% else %}
<li class='read notification' id='{{notification.pk}}'>{{notification.headline|safe}}</li>
{% endif %}
{% endfor %}
<li class='notification all_notifications_link'><a href='{% url "notifications" %}'>Show all</a></li>
</ul>
或在 django-table 中提供更多详细信息:
表格.py
class NotificationTable(tables.Table):
tr_class = tables.BooleanColumn(
visible=False,
empty_values=(),
accessor='active',
)
selection = tables.columns.CheckBoxColumn(
accessor="pk",
attrs={"th__input": {"onclick": "toggle(this)"}},
orderable=False)
message = tables.Column(
accessor='body',
verbose_name='Message')
def render_message(self, value):
return mark_safe(value)
created_date = tables.DateTimeColumn()
def render_tr_class(self, value):
if value is False:
return 'read'
elif value is True:
return 'unread'
class Meta:
model = Notification
它们都正确渲染。在表格上,我可以选择通知,然后单击“标记为已读”,它通过 ajax 调用处理表单并将“活动”设置为 False。在下拉列表中,单击通知(通常是链接)将触发对 mark_single_notification_as_read 的 ajax 调用:
视图.py:
def mark_notifications_as_read(request):
if request.method == 'POST':
selected_pks = request.POST.getlist('selection')
selected_pks = [int(pk) for pk in selected_pks[0].split(',') if pk != 'on']
Notification.objects.filter(pk__in=selected_pks).update(active=False)
table = build_notifications_table(request).as_html()
return HttpResponse(json.dumps(table), content_type='application/json')
def mark_single_notification_as_read(request):
if request.method == 'POST':
notification_id = request.POST.get('notification_id')
Notification.objects.filter(pk=int(notification_id)).update(active=False)
return render(request,
'notifications/notifications_menu_list.html',
{})
else:
print 'not post'
无论哪种方式,一旦 ajax 完成,链接就会变成纯文本。如果我刷新页面,它们又回来了。我不知道为什么。有什么想法吗?
编辑:
忘记了ajax。为什么这很重要?
$("#notification_container").on('click', 'li.unread', function(){
notification_id = $(this).attr('id');
$.ajax({
type: 'POST',
url: "{% url 'mark_single_notification_as_read' %}",
data: {'notification_id' : notification_id},
success: function(data){
$('#notification_container').html(data);
}
});