我必须从Django db中删除记录使用Jquery / Ajax。你能救我吗?
django / views function
def owner(request, identifer):
x = get_object_or_404()
if request.method == "DELETE":
x.objects.delete()
ajax代码:
$(document).ready(function() {
$(".delete").click(function(){
var id_number = this.id;
alert(id_number);
$.ajax({
type: 'DELETE',
url: 'owner/{item.id}/',
data: 'identifer='+id_number,
success: function(){
if(data) {alert("Success!")}
});
});
});
答案 0 :(得分:0)
您必须为数据类型定义
<script>
function deleteCommand(svCommandId) {
var url = $('#service_command_form').attr('action') + svCommandId;
$.ajax({
url: url,
type: "DELETE",
dataType: "json",
beforeSend: function (xhr) {
xhr.setRequestHeader("X-CSRFToken", '{{ csrf_token }}');
},
success: function () {
$('#service_command_' + svCommandId).remove();
addMessage("Deleted data successfully");
},
error: function () {
addMessage("Delete failed!");
}
});
答案 1 :(得分:0)
您没有解释出现了什么问题,但是如果我查看您的代码,您似乎需要更改您的查看代码:
def owner(request, identifer):
try:
x = <YourModelName>.objects.get(id=identifier)
except <YourModelName>.DoesNotExist:
return error message here ...
x.delete()
return success message here ...
您的JS代码中也有错误,您没有使用双括号:
url: "owner/{{item.id}}/"
但更好的是你不应该对你的网址进行硬编码,使用{%url%}模板标签会更好
url: "{% url 'name-of-owner-view' item.id %}"