很难使用jquery / ajax删除对象。我实现了一个表,该表的行包含约会模型中的对象列表。每行中都有一个删除按钮。

对象表的模板为:

<table class="table table-striped table-bordered table-list">
    <thead>
     <tr>
        <th><em class="fa fa-cog"></em></th>
        <th class="hidden-xs">ID</th>
        <th>Patient Name</th>
        <th>Day</th>
        <th>Time</th>
        <th>Location</th>
     </tr>
    </thead>
    <tbody>
        {% for appointment in appointments %}
            <tr>
                <td align="center">
                    <button class="delete_button" id="{{ appointment.id }}">
                        <em class="fa fa-trash"></em>
                    </button>
                </td>
                  <td>1</td>
                <td class="hidden" id="appointment_id">{{ appointment.id }}</td>
                <td>{{ appointment.patient }}</td>
                <td>{{ appointment.day }}</td>
                <td>{{ appointment.time }}</td>
                <td>{% if appointment.clinic %}
                      {{ appointment.clinic }}
                      {% endif %}
                      {% if appointment.hospital %}
                      {{ appointment.hospital }}
                      {% endif %}
                </td>
            </tr>
        {% endfor %}
    </tbody>
</table>


Javascript如下:

$(document).ready(function(){
    $(".delete_button").click(function() {
        var id = $(this).attr('id');
        $.ajax({
            url: "{% url 'deleteappointment' %}",
            data: { 'id' : id },
            beforeSend: function(xhr) {
                xhr.setRequestHeader("X-CSRFToken", {% csrf_token %} );
            },
            success: function(response){
            }
        });
    });
});


当我单击删除按钮时,没有任何反应。我在这里做错了什么?

编辑2
 这在ajax请求中进行:
控制台中的语法错误:

beforeSend: function(xhr) {
      xhr.setRequestHeader("X-CSRFToken", <input type='hidden' name='csrfmiddlewaretoken' value='LUgmNbcWfkIR9KpLi7lzsn0QOk' /> );
                },


如何防止csrftoken标签在此处呈现整个输入字段?

最佳答案

您正在使用{% csrf_token %}模板标记,该标记以html格式插入表单的标记。您可以使用其他类型的括号(引号内)

xhr.setRequestHeader("X-CSRFToken", {% csrf_token %} );


应该

xhr.setRequestHeader("X-CSRFToken", "{{ csrf_token }}");

关于javascript - 使用jquery Ajax在Django中删除Model对象,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/40861518/

10-12 12:55
查看更多