저는 Ajax/jQuery를 처음 사용하며 django 모델을 업데이트하기 위해 http 메서드 PUT
을 사용해야하는 과제를 수행하고 있습니다. 현재 코드가 인을 제외하고 작동합니다. 새로운 수정 버튼을 클릭하고 양식을 제출할 때마다 PUT
요청이 여러 번 + 1 회 실행되고 있습니다.PUT 요청이 두 번 이상 호출되고 있습니다.
예 console.log
를 통해 : 아약스에 대한
(index):121 BUTTON: Pressed modify on product ID: 87
(index):133 GET: Looped through products for ID 87 and set the values in the modal accordingly
(index):153 PUT: Received put request for ID: 87
(index):121 BUTTON: Pressed modify on product ID: 88
(index):133 GET: Looped through products for ID 88 and set the values in the modal accordingly
(index):153 PUT: Received put request for ID: 87
(index):153 PUT: Received put request for ID: 88
(index):121 BUTTON: Pressed modify on product ID: 89
(index):133 GET: Looped through products for ID 89 and set the values in the modal accordingly
(index):153 PUT: Received put request for ID: 87
(index):153 PUT: Received put request for ID: 88
(index):153 PUT: Received put request for ID: 89
코드 :
// MODIFYING A PRODUCT
product_ul.on("click", ".modify", function() { // On clicking modify
var id = $(this).parents('li').attr('id'); // Get the PK which is the ID of the <li>
console.log("BUTTON: Pressed modify on product ID: " + id);
$.ajax({
type: 'GET',
url: 'get/',
dataType: 'json',
success: function (data) {
$.each(data, function (key, value) { // Loop through all products from the json response
if (value.id == id) { // If PK matches product PK from response
$('#dataModal').modal("show"); // Show modal
$('#edit_name').val(value.name); // Set the values
$('#edit_description').val(value.description);
$('#edit_price').val(value.price);
console.log("GET: Looped through products for ID " + id + " and set the values in the modal accordingly");
}
});
}
});
$("#modify_product_form").submit(function (event) { // On submitting the modify form
event.preventDefault(); // Prevent refresh
var product_data = { // Get the values from the form
name: $('#edit_name').val(),
description: $('#edit_description').val(),
price: $('#edit_price').val()
};
$.ajax({
type: 'PUT',
url: 'modify/' + id + '/',
data: product_data,
beforeSend: function (xhr) {
xhr.setRequestHeader("X-CSRFToken", "{{ csrf_token }}");
console.log("PUT: Received put request for ID: " + id);
},
success: function (product) {
var product_html = "<li id=" + product.id + "><button class='delete btn btn-xs btn-danger'><span class='glyphicon glyphicon-remove'></span></button>" +
" <button class='modify btn btn-xs btn-warning'><span class='glyphicon glyphicon-cog'></span></button> " +
product.name + "</li>";
$('#' + product.id).html(product_html); // Change the html to the modified version so it updates the list
$('#dataModal').modal("hide"); // Hide the modal
}
});
});
});
이 웹 페이지는 모습입니다 :
그리고 이후
은 수정 버튼을 클릭 :는 내 유일한 가정은 지금까지 product_ul.on("click", ".modify", function()
따라서 약간의 충돌을 일으키는하지만 난 그들이 중첩하지 않고 var id
을 얻을 수있는 방법을 다른 모르는 내 $("#modify_product_form").submit(function (event)
는 것입니다.
은 어떻게 console.log
모습 기대 :
(index):121 BUTTON: Pressed modify on product ID: 87
(index):133 GET: Looped through products for ID 87 and set the values in the modal accordingly
(index):153 PUT: Received put request for ID: 87
(index):121 BUTTON: Pressed modify on product ID: 88
(index):133 GET: Looped through products for ID 88 and set the values in the modal accordingly
(index):153 PUT: Received put request for ID: 88
(index):121 BUTTON: Pressed modify on product ID: 89
(index):133 GET: Looped through products for ID 89 and set the values in the modal accordingly
(index):153 PUT: Received put request for ID: 89
내가 다른 코드를 제공해야하는지 알려주세요 그리고 당신의 눈이 내 아마추어 코딩을 보는 상처 만약 내가 사과하십시오!
140,256,257
당신은 html을 추가 할 수 있습니다. 그러면이 'id'를 얻는 방법을 알아낼 것입니다. – hodiecode
@hodiecode 아래의 답에서이 것을 알아 냈습니다. 나는 product_ul.on ("click", ".modify", function()') 전에 빈 변수를 선언했다 :'var selected_product = "";와 같은 메서드 내에서'selected_product = $ this (this) '를 할당했다. url : 'modify /'+ selected_product + '부모님 ('li '). attr ('id ');'단순히 $ ("# 수정 _ 제품 _/',' –
이 선택 상품은 전역 변수가 될 것이므로 좋은 연습이 아닙니다. 전역 변수를 사용하지 않으려면'my_shared_object = {}','my_shared_object.selected_product = ""'와 같은 객체를 만드는 것이 좋습니다. . 전역 변수를 사용하지 않는 이유에 대해 자세히 알아보십시오. https://gist.github.com/hallettj/64478 – hodiecode