如何在ajax调用后刷新模板

时间:2018-05-08 21:55:39

标签: ajax django django-forms

我有一个表单,其中包含两个选择输入,一个用于类别,另一个用于子类别,表单应该工作,因为此用户应该在类别中选择一个选项,并且基于该选项,子类别选项应该使用new更新值。但由于某种原因,子类别选项未更新

模板dashboard.html

RewriteEngine On
RewriteBase /

#Your Deny rules here
RewriteCond %{REQUEST_URI} ^(.*)?wp-login\.php(.*)$ [OR]
RewriteCond %{REQUEST_URI} ^(.*)?wp-admin$
RewriteCond %{REMOTE_ADDR} !^123.123.123.123$
RewriteCond %{REMOTE_ADDR} !^123.123.123.123$
RewriteCond %{REMOTE_ADDR} !^123.123.123.123$
RewriteRule ^(.*)$ - [R=403,L]
# End of Your Deny rules

view.py

{% block body %}
<form>
{% csrf_token %}
    <div class="row">
        <div class="input-field col s6 offset-s3">
            <select id="list">
                <option value="" disabled selected>Choose your Category</option>
                <option value="education">University/College</option>
                <option value="hospital">Hospital</option>
                <option value="business">Business Organizations</option>
            </select>
            <label>Categories</label>
        </div>
        <div class="input-field col s6 offset-s3">
            <select>
            <option value="" disabled selected>Choose your Category</option>
            {% for d in data %}
                <option value="">{{ d.username }}</option>
            {% endfor %}
            </select>
            <label>Sub Categories</label> 
        </div>
    </div>
</form>
{% endblock %}

{% block script %}
    <script type="text/javascript">
        $('#list').change(function() {
            $.ajax({
                type: 'POST',
                url: '/dashboard/',
                data: {
                    category: $('#list').val(),
                    csrfmiddlewaretoken: '{{ csrf_token }}'
                }
            });
        });
    </script>
{% endblock %}

1 个答案:

答案 0 :(得分:0)

这是您的子类别,我只需添加一个ID #sub_categories

<select id='sub_categories'>
    <option value="" disabled selected>Choose your Category</option>
    {% for d in data %}
        <option value="">{{ d.username }}</option>
    {% endfor %}
</select>
<label>Sub Categories</label> 

JS

$.ajax({
    type: 'POST',
    url: '/dashboard/',
    data: {
        category: $('#list').val(),
        csrfmiddlewaretoken: '{{ csrf_token }}'
     },
     success:function(response){
         $('#sub_categories').replaceWith($("#sub_categories",response))
     }
 });