Ajax调用未更新模板Django

时间:2018-08-30 18:17:03

标签: ajax django django-templates django-views

以下是详细信息。更改选择选项(即进行ajax调用)后,我能够在视图中获取更新的“ questions_in_topic”变量。 Ajax调用基于下拉列表中的选定值来更新“ questions_in_topic”变量。但是这些更改未反映在模板中。即在模板上,我仍然可以使用旧值。

urls.py

url(r'^interview/add/questions/library', recruiter_views.add_question_library, name='add_question_library'),

views.py

def add_question_library(request):
    question_topics = QuestionTopic.objects.values('question_id__description', 'topic_id__name','question_id','topic_id').order_by('topic_id__name','question_id__description')
    all_topics = Topic.objects.all()
    questions_in_topic = QuestionTopic.objects.values('question_id__description').order_by('question_id__description')

    if request.is_ajax():
        if 'topicId' in request.POST:
            print("xx")
            questions_in_topic = QuestionTopic.objects.filter(topic_id=request.POST['topicId']).values('question_id__description').order_by('question_id__description')
        else:
            print("yy")
            questions_in_topic = QuestionTopic.objects.values('question_id__description').order_by('question_id__description')

    print(questions_in_topic)
    context = { 'question_topics': question_topics, 'all_topics': all_topics,'questions_in_topic':questions_in_topic,}
    return render(request, 'recruiter/add_question_library.html', context)

add_question_library.html

<select id="topic" name="topic_list" class="form-control topic_select">
              {% for topic in all_topics %}
               <option data-topic="{{topic.id}}" value="{{topic.name}}">{{topic.name}}</option>
              {% endfor %}
            </select>    
<ul class="list-unstyled">
            {% for x in questions_in_topic %}
            <li class="list-unstyled">{{ x.question_id__description }}</li>
            {% endfor %}
            </ul>

ajax

var topicId = $(".topic_select option:selected").attr("data-topic");
    $(".topic_select").change(function(){
      var topicId = $(".topic_select option:selected").attr("data-topic");
      $.ajax({
          type: "POST",
          url: "{% url 'recruiter:add_question_library' %}",
          data: {
            topicId: topicId,
            'csrfmiddlewaretoken': '{{ csrf_token }}',
          },
          success: function(){
              // alert("Showing questions from topic " + topicId);
          }
      });
    });

1 个答案:

答案 0 :(得分:2)

随着ajax调用后请求从视图中发出,您可以执行以下操作:

// stuff
success: function(response){
   // $("taget").replaceWith($("target",response));
   $("ul.list-unstyled").replaceWith($("ul.list-unstyled",response));
}

您的项目中可能有多个ul.list-unstyled,建议您为列表添加唯一的ID。