首頁  >  文章  >  web前端  >  django使用ajax post資料出現403錯誤如何解決

django使用ajax post資料出現403錯誤如何解決

亚连
亚连原創
2018-05-24 16:53:282992瀏覽

在django中,使用jquery ajax post數據,會出現403的錯誤,該如何解決呢?以下由我幫大家解決django使用ajax post數據出現403錯誤,需要的朋友可以參考下

#本文透過兩種方法給大家介紹在django中,使用jquery ajax post數據,會出現403的錯誤,具體內容請看下文。

方法一:

如果用jQuery來處理aj​​ax的話,Django直接送了一段解決問題的程式碼。把它放在一個獨立的js檔案中,在html頁面中都引入即可。注意這個js檔案必須在jquery的js檔案引入之後,再引入即可

$(document).ajaxSend(function(event, xhr, settings) { 
 function getCookie(name) { 
  var cookieValue = null; 
  if (document.cookie && document.cookie != '') { 
   var cookies = document.cookie.split(';'); 
   for (var i = ; i < cookies.length; i++) { 
    var cookie = jQuery.trim(cookies[i]); 
    // Does this cookie string begin with the name we want? 
    if (cookie.substring(, name.length + ) == (name + &#39;=&#39;)) { 
     cookieValue = decodeURIComponent(cookie.substring(name.length + )); 
     break; 
    } 
   } 
  } 
  return cookieValue; 
 } 
 function sameOrigin(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 = &#39;//&#39; + host; 
  var origin = protocol + sr_origin; 
  // Allow absolute or scheme relative URLs to same origin 
  return (url == origin || url.slice(, origin.length + ) == origin + &#39;/&#39;) || 
   (url == sr_origin || url.slice(, sr_origin.length + ) == sr_origin + &#39;/&#39;) || 
   // or any other URL that isn&#39;t scheme relative or absolute i.e relative. 
   !(/^(\/\/|http:|https:).*/.test(url)); 
 } 
 function safeMethod(method) { 
  return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method)); 
 } 
 if (!safeMethod(settings.type) && sameOrigin(settings.url)) { 
  xhr.setRequestHeader("X-CSRFToken", getCookie(&#39;csrftoken&#39;)); 
 } 
});

方法二:

在處理post資料的view前加上@csrf_exempt裝飾符

例如

@csrf_exempt 
def profile_delte(request): 
 del_file=request.POST.get("delete_file",&#39;&#39;)

上面是我整理給大家的,希望今後會對大家有幫助。

相關文章:

簡單介紹不用函式庫(框架)自己寫ajax

MVC中基於Ajax和HTML5實作檔案上傳功能

jquery與php結合實作AJAX長輪詢

#

以上是django使用ajax post資料出現403錯誤如何解決的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn