2012-03-25 12 views

Antwort

3

Sie brauchen jQuery dafür nicht. Create a form that performs a POST to the appropriate URL und reichen Sie es ein.

+0

Ok danke! Ich erhalte eine CSRF-Überprüfung fehlgeschlagen 403 Fehler. Ich habe bereits das JavaScript-Snippet hinzugefügt. [link] (https://docs.djangoproject.com/en/dev/ref/contrib/csrf/#ajax) – Zach

+1

Sie müssen das CSRF-Token entweder über '{% csrf_token%}' oder an das JavaScript übergeben Verwenden Sie einen der [CSRF Decorators] (https://docs.djangoproject.com/en/dev/ref/contrib/csrf/#utilities), um die CSRF-Behandlung für die Ansicht zu ändern. –

+0

Ok danke nochmal – Zach

0

Hier ist mein Code zum Senden von Daten per POST an einen Django-Server. Ich besuchte die Seite, die Ignacio vorgeschlagen hatte, und fügte auch csrf hinzu, so dass es mit typischen Djano-Ansichten funktioniert.

// get cookie using jQuery 
    function getCookie(name) { 
     var cookieValue = null; 
     if (document.cookie && document.cookie != '') { 
      var cookies = document.cookie.split(';'); 
      for (var i = 0; i < cookies.length; i++) { 
       var cookie = jQuery.trim(cookies[i]); 
       // Does this cookie string begin with the name we want? 
       if (cookie.substring(0, name.length + 1) == (name + '=')) { 
        cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); 
        break; 
       } 
      } 
     } 
     return cookieValue; 
    } 


    function post_to_url(path, params, method) { 
     method = method || "post"; // Set method to post by default if not specified. 

     // The rest of this code assumes you are not using a library. 
     // It can be made less wordy if you use one. 
     var form = document.createElement("form"); 
     form.setAttribute("method", method); 
     form.setAttribute("action", path); 

     for(var key in params) { 
      if(params.hasOwnProperty(key)) { 
       var hiddenField = document.createElement("input"); 
       hiddenField.setAttribute("type", "hidden"); 
       hiddenField.setAttribute("name", key); 
       hiddenField.setAttribute("value", params[key]); 

       form.appendChild(hiddenField); 
      } 
     } 

     csrfField = document.createElement("input"); 
     var csrftoken = getCookie('csrftoken') 
     console.log("token" + csrftoken) 
     csrfField.setAttribute("type", "hidden"); 
     csrfField.setAttribute("name", "csrfmiddlewaretoken"); 
     csrfField.setAttribute("value", csrftoken) 
     form.appendChild(csrfField) 

     document.body.appendChild(form); 
     form.submit(); 
    } 
Verwandte Themen