我在尝试通过发出Ajax调用来更新我的网站块(包括另一个模板)时遇到问题。需要更新的可以正常运行,但是该模板中的JS脚本无法正常工作(之前,我只是向模板中添加了完整的请求,但是导致解析后的模板的内容翻了一番,但是JS脚本正在运行)。
PD:我是JS的新手,并且对Django有一定的经验(仍然只是在研究Web Apps开发领域)。
我的模板:
{% load staticfiles %}
$(document).ready(function() {
var current_item_id = null;
var current_item_title = null;
var selected_items = null;
// Selección en las tablas
$('.table tr').on('click', function() {
$(this).toggleClass('selected');
});
// Comportamiento del toolbar flotante
$('.table tr').on('click', function() {
selected_items = $('.selected');
current_item_id = $(this).attr('id');
current_item_title = $(this).attr('name');
if (selected_items.length === 0) {
$('.modify-big').attr('disabled', true);
$('.delete-big').attr('disabled', true);
}
else if (selected_items.length > 1) {
$('.modify-big').attr('disabled', true);
}
else {
$('.modify-big').attr('disabled', false);
$('.delete-big').attr('disabled', false);
}
});
});
{% if notifications %}
ItemLink de descargaPlantilla
{% for notification in notifications %}
{{ notification.item_title }}
{% if notification.download_link %}
{{ notification.download_link }}
{% else %}
---
{% endif %}
{{ notification.email_template.name }}{% endfor %}
{% if first_time %}
Últimas notificaciones agregadas.
{% else %}
{% if notifications.has_previous %}
{% else %}
{% endif %}
Página {{ notifications.number }} de {{ notifications.paginator.num_pages }}
{% if notifications.has_next %}
{% else %}
{% endif %}
{% endif %}
{% else %}
No se han encontrado notificaciones.
{% endif %}
Ajax电话:
search_notifications = function(first_time=false, page=null) {
show_div_loader($('#notifications'));
$.ajax({
url: "{% url 'notifications_loader' %}",
data: {
'search_notifications_query': $('#search-notifications-query').val(),
'search_notifications_listing': $('#search-notifications-listing option:selected').val(),
'first_time': first_time,
'page': page,
},
success: function(data){
// Solo necesitamos actualizar la sección #notifications
data = $(data).filter('#notifications').html();
notifications.html(data);
hide_div_loader($('#notifications-container'));
}
});
};
我的观点:
def notifications_loader(request):
[...]
return render(request, 'notifications_search_result.html', {'notifications': notifications, 'first_time': first_time})
如您在Ajax成功函数中所见,我这样做:
data = $(data).filter('#notifications').html();
notifications.html(data);
以前,我在做:
notifications.html(data);
最后一个添加了两倍的解析模板,但是其中的JS脚本正在运行。
我做错了什么?
提前致谢。
编辑:
我不知道这是否是最好的方法,但是我在代码中添加了一个“容器”,然后在其中插入已解析的代码:
在我的主模板中:
JS脚本再次正常工作,而且我没有经过两次解析的模板。现在,因为我正在阅读,我认为这不是使用Django和Ajax的最佳方法,否则我错了吗?也许我只需要将视图返回为JSON并仅替换所需的数据?
我仍然对Ajax + Django和最佳做法有疑问。
谢谢。
解决方案
使用Django进行AJAX时,我是这样进行的:
定义一个路由(视图),该路由将服务于包含ajax调用脚本的默认模板。
为ajax调用添加另一个路由(视图):
def auto_complete(request):
# do some actions and put the results in var
return HttpResponse(simplejson.dumps(var),content_type='application/json')
然后您将在ajax呼叫中呼叫第二条路线
希望对您有帮助