2017-11-08 3 views
1

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

이 웹 페이지는 모습입니다 :

modify button

그리고 이후

은 수정 버튼을 클릭 :

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

+0

당신은 html을 추가 할 수 있습니다. 그러면이 'id'를 얻는 방법을 알아낼 것입니다. – hodiecode

+0

@hodiecode 아래의 답에서이 것을 알아 냈습니다. 나는 product_ul.on ("click", ".modify", function()') 전에 빈 변수를 선언했다 :'var selected_product = "";와 같은 메서드 내에서'selected_product = $ this (this) '를 할당했다. url : 'modify /'+ selected_product + '부모님 ('li '). attr ('id ');'단순히 $ ("# 수정 _ 제품 _/',' –

+0

이 선택 상품은 전역 변수가 될 것이므로 좋은 연습이 아닙니다. 전역 변수를 사용하지 않으려면'my_shared_object = {}','my_shared_object.selected_product = ""'와 같은 객체를 만드는 것이 좋습니다. . 전역 변수를 사용하지 않는 이유에 대해 자세히 알아보십시오. https://gist.github.com/hallettj/64478 – hodiecode

답변

4

당신은 당신의 형태 제품 (// On clicking modify)에 대한 당신의 클릭 핸들러 내부 (// On submitting the modify form) 에 대한 이벤트 핸들러를 제출 추가하고 있습니다. 즉, 제품 ul을 클릭 할 때마다 제출 이벤트 핸들러의 새 사본이 추가됩니다. 양식이 제출되면이 모든 사본이 호출되며 모두 PUT 요청을합니다.

해결 방법은 양식의 제출 처리기를 클릭 처리기 외부로 이동하는 것입니다. 그러면 단 한 번만 추가됩니다.

+1

맞아요. 의심 스러웠습니다. 처음에 나는 더 이상 'id'를 선택할 수 없다고 생각했습니다. 이 작업을 수행하지만 변경된 버튼을 클릭하여 제출 양식에 사용할 때 클릭만으로 변수를 선언하고 할당 할 수 있다는 사실을 깨달았습니다! 감사합니다! 이것에 신선한 눈. –

+0

여러분을 환영합니다! 그리고 네 말이 맞아. 잘 작동 해. –

관련 문제