我该如何循环考虑循环并使用ajax在django中显示结果?

时间:2019-05-23 11:30:03

标签: javascript ajax django django-views

我对django和ajax有疑问,我想用ajax显示forloop的结果。当我提交按钮时,我下面有代码,我的html不附加ajax调用的数据。任何人对此都有好感。感谢您的回答

这是我的观点

def test_ajax(request):
    if request.method == 'POST':
        for i in range(10):
            helloworld(i)
    return render(request, 'test_ajax.html')

def helloworld(request, i):
    data = {
        'status': i
    }
    return JsonResponse(data)

这是我的网址

   path('testajax/', test_ajax),
   path('helloworld/<int:i>/', helloworld, name='ajaxsend')

这是我的html文件{%扩展了'base.html'%}

{% extends 'base.html' %}
{% block content %}
    <div class="container">
        <h1>Hello World</h1>
        <form id="test" method="POST">
            {% csrf_token %}
            <input type="text" id="id_username">
            <button type="Submit" class="btn btn-secondary">Check Token Live</button>
        </form>
        <div id="people">

        </div>
    </div>
{% endblock content %}
{% block script %}
    <script>
        $("#test").on('submit', function (e) {
            e.preventDefault(e);
            $("#people").html('<h2>Hello World</h2>');
            $.ajax({
                url: "/helloworld/",
                success: function(result){
                    alert('Hello world');
                    console.log(result.status)
                    $("#people").append('<h2>' + result.status + '</h2>');
                }
            });
        });
    </script>
{% endblock script %}

0 个答案:

没有答案