2017-11-11 78 views
3

我想解決這個問題約3天,不能這樣做。 我需要從Django中自動增加的id開始。你們能幫我嗎?AJAX功能沒有得到編號

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); 
    } 
    }); 
}; 

回答

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) 

希望這有助於!