[英]Send AJAX request to Django view with vanilla JS
I'm trying to send a GET
AJAX request to a Django view using vanilla JS. 我正在尝试使用香草JS向Django视图发送
GET
AJAX请求。 is_ajax()
passes but I could not retrieve the request object properly. is_ajax()
通过,但是我无法正确检索请求对象。
Here is my JS code. 这是我的JS代码。 With/out
JSON.stringify(data)
doesn't work. 有/无
JSON.stringify(data)
不起作用。
document.querySelector('#testForm').onsubmit = () => {
let data = {category : 'music'};
const request = new XMLHttpRequest();
request.open('GET', 'test/', true);
request.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
request.onload = () => {
const data = JSON.parse(request.responseText);
console.log(data);
}
request.send(data);
return false;
});
And here is my Django view: 这是我的Django视图:
def test(request):
if request.is_ajax():
print('Yes!')
data = {'category': request.GET.get('category', None)}
return JsonResponse(data)
else:
raise Http404
It prints Yes!
它打印
Yes!
to the terminal but I get back a {category: null}
in the console. 到终端,但我在控制台中返回了
{category: null}
。
This JQuery code works and I get the expected {category: "music"}
response: 此JQuery代码有效,我得到了预期的
{category: "music"}
响应:
$.ajax({
url: 'cart/',
type: 'GET',
data: data,
dataType: 'json',
success: function (data) {
console.log(data);
}
});
I'm wondering what I'm missing in the vanilla JS code or in my Django view. 我想知道香草JS代码或Django视图中缺少什么。
GET requests can't have a body, so the data
parameter to request.send
is ignored. GET请求不能具有主体,因此
request.send
的data
参数将被忽略。 You should make it part of the URL itself: 您应该使其成为URL本身的一部分:
request.open('GET', 'test/?category=music', true);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.