2015-06-30 20 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。 –