gpt4 book ai didi

javascript - 403(禁止)

转载 作者:行者123 更新时间:2023-12-03 08:50:10 29 4
gpt4 key购买 nike

我正在尝试发送 $ajax,并且我已经得到了它,但是我必须使用我的表单发送文件,无论是否相同,都没关系。尚未找到 csrf token ,并且出现错误。

我的 JavaScript

    $(document).ready(function() {
var csrf_token = $('input[name="_token"]').val();

$.ajaxSetup({
headers: {
'X-CSRF-Token': $('meta[name="csrf-token"]').attr('content')
}
});

// $("body").bind("ajaxSend", function(elm, xhr, s) {
// if (s.type == "POST") {
// xhr.setRequestHeader('X-CSRF-Token', csrf_token);
// }
// });

window.getCookie = function(cname) { //window for testing in console
var name = cname + "=";
var ca = document.cookie.split(';');
for (var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') c = c.substring(1);
if (c.indexOf(name) == 0) return c.substring(name.length, c.length);
}
return "";
};

function sendPost() {
var data = $('form').serialize();
var file = $(document.getElementById('files').files[0]);

$.ajax({
type: 'POST',
url: '/delling_data_objects/document/',
//data: $('form').serialize(), it's working
data: file, // its don't
enctype: 'multipart/form-data',
headers: window.getCookie('csrftoken')
});
};

$('#submit').on('click', function() {
sendPost();
});
});

我的 View .py

def load_files(request):
form = ApartForm(request.POST)
import pdb
pdb.set_trace()
if form.is_valid():
form.save()
file_form = request.POST['file']
for f in file_form:
with open(f) as dest:
for chunk in f.chunks():
dest.write(chunk)
else:
return HttpResponse('form is not valid')
return HttpResponse('ok')

最佳答案

你做得不对。感觉就像您发送了两次 requestHeader 。(编辑:没关系,没有看到代码的一部分被注释)根据您的代码,尝试如下操作:

    function sendPost() {
var data = $('form').serialize();
var file = $(document.getElementById('files').files[0]);
var csrftoken = getCookie("csrftoken");
$.ajax({
method: "POST",
url: '/delling_data_objects/document/',
data: data,
beforeSend: function(xhr, settings) {
if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
xhr.setRequestHeader("X-CSRFToken", csrftoken);
}
},
success: function(data) {
// whatever you want to do
}
});
}


$('#submit').on('click', function() {
sendPost();
});


var getCookie = function(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;
};

var csrfSafeMethod = function (method) {
// these HTTP methods do not require CSRF protection
return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
};

关于javascript - 403(禁止),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32713261/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com