2015-06-30 21 views
0

我有一個靜態HTML頁面與引導和jQuery構建。有一個聯繫我們的形式,我已經在其上設置了Ajax Post調用我的django應用程序。Ajax郵政表格跨域不同應用程序

靜態html頁面託管在Windows服務器上,我的django應用程序託管在heroku上。 在ajax調用我通過jquery獲取csrf標記,但它返回null。

$("#submit_button").click(function() { 
     var from_name   = $("#Name").val(); 
     var from_email   = $("#email").val(); 
     var story_subject  = $("#Message").val(); 
     var csrftoken = getCookie('csrftoken'); 
     console.log(from_name); 
     console.log(from_email); 
     console.log(story_subject); 
     console.log(csrftoken); 
     $.ajax({ 
      type: 'POST', 
      url: 'http://www.example.com/users/api-26/', 
      useDefaultXhrHeader: false, 
      crossDomain: true, // enable this 
      dataType: 'jsonp', 
      data: { 
      'from_name': from_name, 
      'from_email':from_email, 
      'story_subject':story_subject, 
      'csrfmiddlewaretoken': csrftoken 
      }, 
      beforeSend: function(xhr) { 
      xhr.setRequestHeader('X-CSRFToken', $.cookie('csrftoken')), 
      }, 
      success: function (response_data) { 
      var _result = JSON.parse(response_data); 
      if(_result.status == 'True'){ 
       $('#myModal').hide(); 
       console.log("sent"); 
      }else{ 
       console.log(response.error.message); 
      } 
      }, 
      error: function(xhr, textStatus, thrownError) { 
      console.log(xhr.status + ": " + xhr.responseText); 
      } 

     }); 
     return false; 
     }); 

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 = cookies[i].trim(); 
      // 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; 
} 

和Django的視圖

@csrf_protect 
@require_http_methods(["POST"]) 
def Contactus(request): 

正如我有CSRF令牌的問題,有沒有在進行此調用安全的任何其他方式。

+1

由於瀏覽器安全措施,即使使用正確的CSRF令牌,跨域POST也不起作用。爲了得到它的工作,你需要設置CORS(http://stackoverflow.com/a/7605119/1059782)。 –

回答

0

如前所述,您需要在您的端點上啓用CORS(跨源資源共享),以便執行Ajax操作或使用JSONP進行響應,我建議這是一種更簡單的方法。

要啓用CORS,您可以使用django-cors-headers軟件包,該軟件包有幾個可供選擇的選項,如白名單。

+0

我已經設置好了,但仍然是錯誤的。 –

+0

'console.log(csrftoken);'這在我的控制檯中輸出null。 –