2013-05-01 97 views
1

下面是我的Ajax POST請求獲得403 Forbidden錯誤甚至提供CSRF令牌

這是模板

<script type="text/javascript"> 
    function submit_vote(){ 
     callback = function(data){ 
      alert(data.message); 
     }; 

     $.post("{{request.get_full_path}}vote",{ 
      "rating" : $('#{{hash_id}}').raty('score') 
     }, callback, "json"); 
    } 
</script> 

<div class="rating" id="{{hash_id}}" onclick="submit_vote()"></div> 

在景色,這裏是後

這是認爲,呈現其中存在Ajax腳本的模板

@csrf_protect 
def show_rating(request, **kwargs): 
    .... 
    .... 
    return render_to_response("rating.html", 
       context, 
       context_instance = RequestContext(request)) 

這是需要POST請求的視圖牛逼

@login_required 
@csrf_protect 
def submit_vote(request, **kwargs): 
    if not request.method == "POST": 
     raise Http404 

    ... 
    ... 

    data = {"error" : False, "message" : "Thanks"} 
    data = simplejson.dumps(data) 
    return HttpResponse(data, mimetype="application/javascript") 

在嘗試上述代碼中,我得到403 Forbidden錯誤。通過使用Django文檔,我添加了另一個劇本到現有的代碼(在頂部)

<script type="text/javascript"> 
function csrfSafeMethod(method) { 
    // these HTTP methods do not require CSRF protection 
    return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method)); 
} 
function sameOrigin(url) { 
    // test that a given url is a same-origin URL 
    // url could be relative or scheme relative or absolute 
    var host = document.location.host; // host + port 
    var protocol = document.location.protocol; 
    var sr_origin = '//' + host; 
    var origin = protocol + sr_origin; 
    // Allow absolute or scheme relative URLs to same origin 
    return (url == origin || url.slice(0, origin.length + 1) == origin + '/') || 
     (url == sr_origin || url.slice(0, sr_origin.length + 1) == sr_origin + '/') || 
     // or any other URL that isn't scheme relative or absolute i.e relative. 
     !(/^(\/\/|http:|https:).*/.test(url)); 
} 
$.ajaxSetup({ 
    beforeSend: function(xhr, settings) { 
     if (!csrfSafeMethod(settings.type) && sameOrigin(settings.url)) { 
      // Send the token to same-origin, relative URLs only. 
      // Send the token only if the method warrants CSRF protection 
      // Using the CSRFToken value acquired earlier 
      xhr.setRequestHeader("X-CSRFToken", csrftoken); 
     } 
    } 
}); 
</script> 

現在我越來越

Uncaught ReferenceError: csrftoken is not defined 

錯誤..

如何解決呢?實際上,我不知道Ajax和Jquery和JS ..只是試圖從網上的教程建立一個簡單的請求!

回答

1

您只需在您的發佈請求中發送csrfmiddlewaretoken,它應該被修復。

$.post("{{request.get_full_path}}vote",{ 
     "rating" : $('#{{hash_id}}').raty('score'), 
     "csrfmiddlewaretoken": {{csrf_token}}, 
    }, callback, "json"); 

您不需要任何其他腳本。