你好,我想使用 AJAX 或 JavaScript 删除 Django 对象,并在单击删除时显示确认消息,但我不知道如何完成 AJAX 请求。
View .py
def delete(request,id):
try:
inta = work.objects.get(pk=id)
inta.delete()
except:
pass
return HttpResponseRedirect(reverse('home'))
url.py
url(r'^delete/(?P<id>\d+)/$',views.delete, name='delete')
html:
{& for app in apps &}
<p>{{ app.item0 }}</p>
<p>{{ app.item1 }}</p>
<p>{{ app.item2 }}</p>
<button data-object-id="{{ app.id }}">remove</button>
{% endfor %}
$('button').on('click', function(){
var confirmation = confirm("are you sure you want to remove the item?");
if (confirmation) {
// execute ajax
alert('removed');
}
})
最佳答案
还有更方便的方式来编写AJAX代码:
$('button').on('click', function(){
let confirmation = confirm("are you sure you want to remove the item?");
if (confirmation) {
let object_id = $(this).attr('data-object-id');
let url = `delete/${object_id}/`;
$.ajax({
url: "example.html/my/example",
data: {
'csrfmiddlewaretoken': "{{ csrf_token }}"
},
type: "DELETE",
dataType: "json"
}).done(
function(){alert("Deleted");}
).fail(
function(){alert("Error");}
)
});
}
})
关于javascript - django 使用 AJAX 或 javascript 删除对象并确认,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55599924/