简体   繁体   中英

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. is_ajax() passes but I could not retrieve the request object properly.

Here is my JS code. With/out JSON.stringify(data) doesn't work.

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:

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! to the terminal but I get back a {category: null} in the console.

This JQuery code works and I get the expected {category: "music"} response:

$.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.

GET requests can't have a body, so the data parameter to request.send is ignored. You should make it part of the URL itself:

request.open('GET', 'test/?category=music', true);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM