2012-03-25 96 views

回答

3

你不需要這個jQuery。 Create a form that performs a POST to the appropriate URL並提交。

+0

好的,謝謝!我得到一個CSRF驗證失敗403錯誤。我已經添加了JavaScript片段。 [鏈接](https://docs.djangoproject.com/en/dev/ref/contrib/csrf/#ajax) – Zach 2012-03-25 21:26:46

+1

您需要通過'{%csrf_token%}'將CSRF令牌傳遞給JavaScript或使用[CSRF裝飾器]之一(https://docs.djangoproject.com/en/dev/ref/contrib/csrf/#utilities)來修改視圖上的CSRF處理。 – 2012-03-25 21:28:58

+0

好的再次感謝 – Zach 2012-03-25 21:37:52

0

這是我通過POST發送數據到Django服務器的代碼。我瀏覽了Ignacio建議的站點,並添加了csrf,以便與典型的Djano視圖配合使用。

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