我试图解决这个问题大约3天而不能这样做。 我需要在Django中获取自动递增的id。你能帮帮我吗。
function add_product(){
event.preventDefault();
var name = $("#name").val();
var price = $("#price").val();
var description = $("#description").val();
var dataString = [name, description, price];
var n = dataString.length;
$.ajax({
type: "POST",
url: "add/",
data: {
csrfmiddlewaretoken: '{{ csrf_token }}',
name: $('#name').val(),
email: $('#price').val(),
description: $('#description').val(),
},
dataType: "json",
success: function(){
var button = $('<button class="reo" onclick="delete_product('+ I need to take the id from the database+')" id="my" value="">Delete</button>');
var row = $('<tr>');
for(var i = 0; i < n; i++) {
row.append($('<td>').html(dataString[i]));
}
$('#tableForm').append(row);
$('#tableForm').append(button);
}
});
};
答案 0 :(得分:4)
将返回的数据传递给您的成功函数,如下所示,
success:function(data) {
...
var button = $('<button class="reo" onclick="delete_product('+ data +')" id="my" value="">Delete</button>');
...
}
您的视图应该在HttpResponse中返回新创建的ID。例如(假设是python / django后端),
Return HttpResponse(new_record.id, status=200)
希望这有帮助!