首页 > 解决方案 > Django - ajax 轮询结果在同一页面上

问题描述

我正在学习 django,我的应用程序需要帮助。在一个页面中,我有一个民意调查:我希望在用户投票后,民意调查表单消失,并出现一个 div #ajaxresults,其中包含每个选项的更新投票。我正在使用 ajax 调用,但无法返回更新后的投票。

如果我直接调用'/polls/4/results',我可以看到正确的列表,但我不能在表单的同一页面上包含该块。我错过了什么?

网址.py

app_name = 'polls'
urlpatterns = [
    path('', views.index, name='list'),
    path('<int:question_id>/', views.detail, name='detail'),
    path('<int:question_id>/results/', views.results, name='results'),
    path('<int:question_id>/vote/', views.vote, name='vote'),
]

视图.py

def results(request, question_id):
    question = get_object_or_404(Question, pk=question_id)
    #return render(request, 'polls/results.html', {'question': question})
    return redirect(question.get_absolute_url())

@require_POST
def vote(request, question_id):
    question = get_object_or_404(Question, pk=question_id)
    selected_choice = question.choice_set.get(pk=request.POST['selectionId'])
    selected_choice.votes += 1
    selected_choice.save()
    return redirect('polls:results', question_id = question_id)

详细模板(扩展 base.html)

<form id="quiz-module" action="#">
 <input type="hidden" id="pollId" name="pollId" value="{{question.id}}">
{% csrf_token %}
    <fieldset>
        <h2>{{ question.question_text }}</h2>
        <ul>
        {% for choice in question.choice_set.all %}
            <li><input type="radio" name="opt" value="{{ choice.id }}" {% if forloop.first %}required {%endif%}/>{{ choice.choice_text }}</li>
        {% endfor %}
        </ul>
    </fieldset>
</form>
<section id="quiz-results">
    <h3>Your vote</h3>
    <p id="ajaxresults"></p>
    <h3>All votes</h3>
    <dl>
        {%block updated_results %}{% endblock %}
    </dl>
</section>

模板投票为空

模板结果(不扩展)

{%block updated_results %}
    {% for choice in question.choice_set.all %}
        <dt>{{ choice.choice_text }}:  </dt><dd id="choiceId-{{ choice.id }}">{{ choice.votes }}</dd>
    {% endfor %}
{% endblock %}

js

var args = { 
                type:"POST", 
                url:"/polls/"+pollId+"/vote/", 
                data:data, 
                success: function( data ) {
                    //print your vote
                    results.children('#ajaxresults').html(selectionText); 
                    form.hide('fast');
                    results.show('fast');
                },
                error: function(xhr, status, error) {
                  alert(error+'<br/>'+"Sorry. Can't submit your vote. Please, reload the page and try again")
                },
            };
            $.ajax(args);

标签: ajaxdjangoredirect

解决方案


推荐阅读