2017-11-08 27 views
1

私はAjax/jQueryを初めて使用しており、httpメソッドPUTを使用してdjangoモデルを更新する必要があります。現在のコードはという1つの問題PUTのリクエストは、新しい変更ボタンをクリックしてフォームを送信するたびに複数回+ 1回実行されています。 AJAX用PUTリクエストが複数回呼び出されています

(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 

コード:

console.log経由例に

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

これは、Webページがどのように見えるかです:

modify button

し、変更ボタンをクリックした後:

modal

私の唯一の仮定は、これまで$("#modify_product_form").submit(function (event)product_ul.on("click", ".modify", function()内したがって、いくつかの競合を引き起こしているということですが、私は、ネストされたそれらをせずにvar idを得ることができる方法が他に知りません。私は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 

私は他のコードを提供しなければならないなら、私が知っているし、あなたの目は私のアマチュアコーディングを見てから傷つける場合、私は謝罪してください!

+0

あなたはhtmlを追加して、このidを取得する方法を見つけました – hodiecode

+0

@hodiecode私は以下の答えからこれを理解しました。私は空の変数を 'product_ul.on '(" click "、" .modify "、function()'の前に 'var selected_product =" "'のように宣言し、メソッド 'selected_product = $ this(this)')に割り当てました。それは単に$( "#id")で '$("#modify_product_form ")を参照するだけです。/'、' –

+0

この選択されたプロダクトはグローバル変数になります。それは良いことではありません。グローバル変数を使用しないように、 'my_shared_object = {}'や 'my_shared_object.selected_product =グローバル変数を使用しない理由については、https://gist.github.com/hallettj/64478 – hodiecode

答えて

4

あなたのフォームの提出イベントハンドラ(// On submitting the modify form)製品(// On clicking modify)用内部のあなたのクリックハンドラを追加しています。つまり、製品ulをクリックするたびに、サブミットイベントハンドラの新しいコピーが追加されます。フォームが提出されると、これらのコピーがすべて呼び出され、それらはすべてPUT要求を行います。

解決策は、フォームの送信ハンドラを途中で、つまりクリックハンドラの外側に移動することです。それは一度だけ追加されることを確認します。

+1

を参照してください。私は疑いがあったように、最初は「id」を選択できないと思っていました。これを行うには、私はちょうど私が変更ボタンをクリックし、それを私の送信フォームで使用すると、クリックの外に変数を宣言し、それを割り当てることができることを実現しました!これに新鮮な目。 –

+0

あなたは大歓迎です!そして、あなたは正しい、それはうまくいくはずです。 –

関連する問題