Привет, классные люди!
Так много вопросов о Переполнение стека касаются "Как обновить dom через jquery (from the same view/url)" Это не то, что я ищу.
На веб-сайте, большая часть которого работает с ajax, мне интересно, как обновить часть HTML DOM при запросе внешний вид django.
Позвольте мне пояснить некоторые примеры:
У меня такое представление, которое отправляет all_users в шаблон
def usersList(request):
all_users = User.objects.all()
return render(request,'administration/users-list.html',{'all_users':all_users})
В шаблоне я прохожу через all_users ... 2-й <span> отражает activation state пользователя.
{% for u in all_users %}
<span>{{forloop.counter}}.- {{u.name}} <span>
<span id='user_{{u.id}}_state'>
<button data-id='{{u.id}}' type='button' class='css-btn btn-circle'>
{% if u.is_activate %} Active{% else %}Inactive{% endif %}
</button>
<span>
{% endfor %}
С помощью jquery я отправляю запрос конкретному представлению, отвечающему только за activate или deactivate за учетную запись пользователя. Мы можем использовать activate/deactivate во многих частях веб-сайта, поэтому я делаю это с другой точки зрения.
Вот вид:
def deactivateUser(request):
user = request.user
if user.has_perm('is_admin') and request.is_ajax() and request.method == 'POST':
id_user = request.POST.get('id')
targeted_user = get_object_or_deny(User,id=id_user)
# get_object_or_deny is my own function
it will get the object or raise PermissionDenied otherwise
if targeted_user.is_activate:
targeted_user.is_activate = False
state = 'deactivated'
else:
targeted_user.is_activate = True
state = 'activated'
targeted_user.date_update_activation = NOW() # own function
targeted_user.save()
return JsonResponse({'done':True,'msg':'User successfully %s' %s state})
# Here we return a JsonResponse
raise PermissionDenied
Итак, как я могу обновить Dom с помощью следующих материалов jquery, чтобы получить текущее состояние каждого пользователя
$(document).on('click','.btn-circle',function(){
var id = $(this).data("id");
$.ajax({
url:'/u/de-activate/?ref = {{ request.path }}',
type:'post',
data:{
csrfmiddlewaretoken:"{{ csrf_token }}",
id:id,
},
success:function(response){
$("#user_"+id+"_state").replaceWith($("#user_"+id+"_state",response));
if (response.created) alert(response.msg);
},
error:function(){
alert("An error has occured, try again later");
}
});
});
Note that
all_usersis required to loop through.deactivateUser()return a Json response, even though it doesn't returned it, it will not matter.
Целевая часть $("#user_"+id+"_state") становится пустой, имеет смысл, потому что ответ - Json, а не string html response.



![Безумие обратных вызовов в javascript [JS]](https://i.imgur.com/WsjO6zJb.png)


Вы можете отправить HTTP-ответ, а не json.
Во-первых, просто переместите свой html, который хотите изменить. в этой ситуации,
{% for u in all_users %}
<div id = "user-part">
<span>{{forloop.counter}}.- {{u.name}} <span>
<span id='user_{{u.id}}_state'>
<button data-id='{{u.id}}' type='button' class='css-btn btn-circle'>
{% if u.is_activate %} Active{% else %}Inactive{% endif %}
</button>
<span>
</div>
{% endfor %}
Затем сохраните его, т.е. user_part.html
Во-вторых, заставьте ваше представление возвращать HttpResponse с этим html и контекстом. Вы можете использовать HttpResponse или render_to_response. Рекомендую render_to_response.
context = {
'all_users': all_users,
}
return render_to_response(
'path_to/user_part.html',
context=context,
)
В-третьих, вы просто меняете скрипт для замены вашего html.
success: function(response){
$('#user-part').html(response);
prevent();
}
что у вас есть, когда вы обновляете дом так, как вы это делаете?