Ajax调用未更新模板Django [英] Ajax call not updating template django
本文介绍了Ajax调用未更新模板Django的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
以下是详细信息。更改选择选项(即进行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);
}
});
});
推荐答案
在ajax调用之后,请求就从视图中发出了,您可以这样做:
With the request coming from view after the ajax call, you can do this:
// stuff
success: function(response){
// $("taget").replaceWith($("target",response));
$("ul.list-unstyled").replaceWith($("ul.list-unstyled",response));
}
您可能有多个 ul.list-unstyled
在您的项目中,建议您在列表中添加一个唯一ID。
You may have multiple ul.list-unstyled
in your project, I suggest that you add a unique ID to the list.
这篇关于Ajax调用未更新模板Django的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文