我正在尝试通过AJAX GET请求将localStorage
中的数据发送给Django,但Django服务器从未收到过它。我有信心localStorage("preselection")
中有console.log
中的数据。这是我的JavaScript代码段,该代码段位于index.html(是一个初学者,因此很抱歉,如果这是基础知识,并且我暂时不使用jQuery):
var preselection = localStorage.getItem("preselection");
function previous_selection () {
if (localStorage.getItem("preselection") != null) {
console.log("PRESELECTION IS: ", preselection);
const data = new FormData();
data.append("preselection", preselection);
const request = new XMLHttpRequest();
request.open('GET', '/');
request.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));
request.send(data);
request.onload = () => {
var url = '/prebasket';
window.location.href = url;
};
return false;
}
}
previous_selection();
以下是我在views.py
中的观点。我尝试了request.GET.dict()
,request.GET.get()
,request.GET.copy()
等,以防万一,我的数据以JSON格式出现,但是Django只是得到了一个空的{}
或Null
为q_preselection
:
@login_required
def index(request):
q_preselection = request.GET.dict()
print(q_preselection) # comes back empty
context = {
#irrelevant
}
return render(request, "pizza/index.html", context)
答案 0 :(得分:2)
XMLHttpRequest send()
未传递GET的正文数据
send()
接受一个可选参数,可让您指定 请求者的身体;这主要用于诸如PUT之类的请求。如果 请求方法为 GET 或HEAD,body参数为忽略, 请求正文设置为null。
改为使用POST,您几乎永远都不希望BODY发出GET请求(参数应该通过GET的URL传递)