我尝试解决此问题大约 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);
}
});
};
最佳答案
将返回的数据传递给您的成功函数,如下所示,
success:function(data) {
...
var button = $('<button class="reo" onclick="delete_product('+ data +')" id="my" value="">Delete</button>');
...
}
您的 View 应该在 HttpResponse 中返回新创建的 id。例如(假设 python/django 后端),
Return HttpResponse(new_record.id, status=200)
希望这有帮助!
关于jquery - AJAX 函数未获取 id,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47232927/