2017-02-06 2 views
1

У меня есть querysets для комментариев, которая выглядит так:Можно ли изменить запрос с помощью AJAX?

comment_list = Comment.objects.filter().order_by('-score__upvotes') 
new_comments_list = Comment.objects.filter().order_by('-timestamp') 

Тогда мой шаблон

{% for comment in comment_list %} 
    {{ comment }} 

... 

Есть ли способ изменить {% for comment in comment_list %} к {% for comment in new_comments_list %} с помощью AJAX (без обновления страницы)?

Возможно изменить значение comment_list на Comment.objects.filter().order_by('-timestamp')?

ответ

1

Запросы AJAX возникают, когда разработчик (вы) так говорит. Если, например, вы установили прослушиватель событий на «Щелчок» определенной кнопки, чтобы выполнить запрос AJAX, тогда будет сделан запрос AJAX.

Допустим, у вас есть прослушиватель событий, который «прослушивает» событие click на определенной кнопке с id=my-button.

{# Place this as a separate html file, say "ajax_comments.html" #} 
<div id="my-placeholder"> 
    {% for comment in comments %} 
     {{ comment }} 
    {% endfor %} 

    <button id="my-button">Update comments</button> 
</div> 
{# END OF PLACE THIS #} 

{# ############################################################### #} 

{# Begin of your main HTML template, say "my_template.html" #} 

.... 

{% include 'path/to/ajax_comments.html' %} 

.... 

// make an Ajax call (GET request) to the same url, using jQuery. 
$(document).ready(function() { 
    $('#my-button').on('click', function() { 
     $.ajax({ 
      'method': 'GET', // defaults to GET. Set POST if you like, but be aware of the CSRF token submission too! 
      'url': '.', // submit to the same url 
      'data': {}, // pass here any data to the server. You can omit it. 
      success: function(dataReturned) { 
       // This function will run when server returns data 
       $('#my-placeholder').replaceWith(dataReturned); 
      } 
     }); 
    }); 
}); 

{# END OF "my_template.html" #} 

Выполнено с использованием HTML, JS. Теперь к вашему views.py.

def my_view(request): 
    if request.is_ajax(): 
     # If you have passed any data through the 'data' property 
     #you can get it here, according to the method used. 
     my_data = request.GET.get('data-name') 
     comments = Comment.objects.filter().order_by('-timestamp') 
     # Note that we are passing the 'ajax_comments.html' template. 
     return render(request, 'ajax_comments.html', {'comments': comments}) 

    comments = Comment.objects.filter().order_by('-score__upvotes') 
    return render(request, 'my_template.html', {'comments': comments}) 
  1. Кнопка нажата в шаблоне
  2. запрос AJAX сделан на сервер
  3. Внутри ваших взглядов, вы обращаться с этим видом запроса и вы возвращаете HTML часть с новым запросset.
  4. Это возвращение не отображается непосредственно в шаблон, а идет к функции $.ajax(), которая ждет этого.
  5. После получения, он делает то, что мы написали, чтобы сделать (заменить данные, div «s с новыми)

Надеется, что это помогает!

+0

Спасибо за ответ. Мне удалось изменить запрос, используя очень похожий код для вашего, но по какой-то причине javascript не работает над недавно загруженным дочерним шаблоном. Вы знаете, почему? Я задал вопрос здесь: http://stackoverflow.com/questions/42126427/js-stops-working-on-child-template-when-i-perform-an-ajax-call-to-change-the- дие? noredirect = 1 # comment71422842_42126427 – Zorgan

 Смежные вопросы

  • Нет связанных вопросов^_^