2017-11-08 1 views
1

Ich bin neu bei Ajax/jQuery und ich mache eine Aufgabe, wo ich HTTP-Methode PUT verwenden muss, um ein Django-Modell zu aktualisieren. Der Code, den ich derzeit habe, funktioniert mit Ausnahme von ein Problem: die PUT Anfrage wird mehrmals ausgeführt + 1 Mal, wenn ich auf eine neue Schaltfläche zum Ändern klicken und das Formular absenden.PUT Anfrage wird mehr als einmal aufgerufen

Beispiel über 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 

-Code für Ajax:

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

Dies ist, wie die Webseite aussieht:

modify button

und nach der Schaltfläche ändern klicken:

modal

Meine einzige Annahme so weit, dass die $("#modify_product_form").submit(function (event) innerhalb product_ul.on("click", ".modify", function() so einige Konflikte verursachen, aber ich weiß nicht, wie sonst könnte ich die var id bekommen, ohne sie verschachtelte zu haben.

Wie erwarte ich, dass die console.log aussehen:

(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 

Bitte lassen Sie mich wissen, wenn ich einen anderen Code zur Verfügung stellen sollte, und ich entschuldige mich, wenn Sie Ihre Augen nicht sehen meine Amateur-Codierung verletzt!

+0

Sie könnten HTML hinzufügen, dann würden wir herausfinden, wie Sie diese ID erhalten – hodiecode

+0

@hodiecode Ich fand dies aus der Antwort unten. Ich habe eine leere Variable vor 'product_ul.on '(" click "," .modify ", function()' so deklariert: 'var selected_product =" ";' und sie in der Methode zugewiesen: 'selected_product = $ (this). eltern ('li'). attr ('id'); 'dann referenziert man einfach in' $ ("# modify_product_form"). submit (function (event) 'so:' url: 'modify /' + selected_product + '/', ' –

+0

großartig, aber dieses selected_product wird Globale Variable sein ... und das ist keine gute Übung.Erstens ein Objekt wie' my_shared_object = {} 'und dann' my_shared_object.selected_product = "" 'zu erstellen, um die Verwendung globaler Variablen zu vermeiden Lesen Sie mehr darüber, warum keine globalen Variablen zu verwenden sind https://gist.github.com/hallettj/64478 – hodiecode

Antwort

4

Du fügst ein Event-Handler für das Formular (// On submitting the modify form) innerhalb Ihre Click-Handler für das Produkt (// On clicking modify) einreichen. Das bedeutet, dass jedes Mal, wenn Sie auf ein Produkt ul klicken, eine neue Kopie des Submit-Event-Handlers hinzugefügt wird. Wenn das Formular gesendet wird, werden alle diese Kopien aufgerufen, und sie alle führen eine PUT-Anforderung aus.

Die Lösung wäre, den Submit-Handler des Formulars aus dem Weg zu schieben, also außerhalb des Click-Handlers. Das würde sicherstellen, dass es nur einmal hinzugefügt wird.

+1

Richtig! Genau wie ich vermutet habe. Zuerst dachte ich, ich wäre nicht in der Lage, die 'id' nicht mehr zu wählen dies zu tun, aber ich habe gerade festgestellt, dass ich eine Variable außerhalb des Klicks deklarieren und zuweisen kann, wenn der Modify-Button geklickt wird, dann benutze es in meinem Formular! Danke !! Alles, was ich brauchte, war frische Augen darauf. –

+0

Gern geschehen! Und du hast Recht, das sollte gut funktionieren. –

Verwandte Themen