@nurzhannogerbek

AJAX обновление списка объектов?

Помогите разобраться. В своём Django проект у меня есть страница `product_detail`, где есть часть с комментариями. После успешного добавления нового комментария через AJAX заметил, что обновилась страница, а не часть со списком комментариев как я планировал и к тому же url адрес поменялся на `comment_add`.

Как правильно обновить именно список комментариев и оставить url адрес на `product_detail`?

product_detail.html:
<div class="card">
   <div class="card-block">
      <table id="comment-table">
         <thead>
            <tr>
               <th>Author</th>
               <th>Date</th>
               <th>Comment Text</th>
            </tr>
         </thead>
         <tbody>
            {% include 'project/comment_list.html' %}
         </tbody>
      </table>
   </div>

   <div class="card-footer">
   <form method="post" class="comment-form" id="comment-form" action="{% url 'project:comment_add' project_code=project.code product_code=product.code %}">
      {% csrf_token %}
         {% for field in form %}
         <div class="form-group{% if field.errors %} has-error{% endif %}">
            {% render_field field class="form-control" %}
            {% for error in field.errors %}
                 <p class="help-block">{{ error }}</p>
            {% endfor %}
         </div>
         {% endfor %}
         <button type="submit" class="btn btn-primary">Send</button>
      </form>
   </div>
</div>


urls.py:
url(r'^(?P<project_code>[0-9a-f-]+)/(?P<product_code>[0-9a-f-]+)/product_detail/$',
        product_detail,
        name='product_detail'),

    
    url(r'^(?P<project_code>[0-9a-f-]+)/(?P<product_code>[0-9a-f-]+)/comment_add/$',
        comment_add,
        name='comment_add'),


views.py:
def comment_add(request, project_code, product_code):
    data = dict()
    project = get_object_or_404(Project, pk=project_code, status='open')
    product = get_object_or_404(Product, pk=product_code)
    if request.method == 'POST':
        form = CommentForm(request.POST)
        if form.is_valid():
            comment = form.save(commit=False)
            comment.author = request.user
            comment.save()
            product.comments.add(comment)
            data['form_is_valid'] = True
            data['html_comment'] = render_to_string('project/comment_list.html', {'product': product})
            form = CommentForm()
        else:
            data['form_is_valid'] = False
    else:
        form = CommentForm()
    context = {'project': project, 'product': product, 'form': form}
    return render(request, 'project/product_detail.html', context)


javascript:
$("#comment-form").submit(function(event) {
    event.preventDefault();
    var form = $(this);
    $.ajax({
        url: form.attr("action"),
        data: form.serialize(),
        type: form.attr("method"),
        dataType: 'json',
        success: function (data) {
            if (data.form_is_valid) {
                $("#comment-table tbody").html(data.html_group_task_comment);
            }
            else {
                $("#comment-form").html(data.html_group_task_comment_form);
            }
        }
    });
    return false;
});
  • Вопрос задан
  • 789 просмотров
Решения вопроса 1
ThunderCat
@ThunderCat Куратор тега JavaScript
{PHP, MySql, HTML, JS, CSS} developer
Судя по всему, event.preventDefault(); не отрабатывает, что легко проверить, выставив алерт или консоле лог после этой строки. И вроде оно не там должно быть, а после отработки всего что нужно по событию выполнить.

PS: тут немного о jq и event.preventDefault()
Ответ написан
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы