简体   繁体   中英

Django view not getting ajax request

I have a script in my template that tries to send data to a django view during onbuttonclick event. My problem is that the request doesn't seem to make it to the view. The browser console sees the request properly and all, but the django view does't even return true when i call request.is_ajax().

request.method returns GET instead of POST, and the data is empty. This behavior is persistent regardless of the request type.

html

<a onclick="setGetParameter(this)" pid="some_id">Some Text</a>

.js

<script>
  var csrftoken = Cookies.get('csrftoken');

  function setGetParameter(el){

      var stuff = $(el).attr('pid');

      $.ajax({
        type: 'POST',
        headers: { "X-CSRFToken": csrftoken },
        url: '/view_url/',        
        data: {'datatopass': stuff},
        success: function(response){
          alert(response);
        }
      });
  }
  </script>

urls.py

path('view_url/', views.test),
path('', views.home),

views.py

def test(request): 
    output = request.is_ajax()
    return HttpResponse(output)

In Django 3.1 is_ajax() method is deprecated. See Miscellaneous Django 3.1

So for Django >= 3.1 you can do it like that:

if request.headers.get('x-requested-with') == 'XMLHttpRequest':
    is_ajax = True
else:
    is_ajax = False

And make sure that the following line added in AJAX request headers:

"X-Requested-With": "XMLHttpRequest"

I would be use jQuery click method:

<a pid="some_id">Some Text</a>

<script>
var csrftoken = Cookies.get('csrftoken');

function setGetParameter(el){

    var stuff = $(el).attr('pid');

    $.ajax({
        type: 'POST',
        headers: { "X-CSRFToken": csrftoken },
        url: '/view_url/',        
        data: {'datatopass': stuff},
        success: function(response){
            alert(response);
        }
    });
}

$(document).ready(function(){
    $('a[pid]').click(function(){
        setGetParameter(this);
    });
});
</script>

Also I would be use JsonResponse objects :

from django.http import JsonResponse

def test(request): 
    output = request.is_ajax()
    return JsonResponse({'is_ajax': output})

In order to serialize objects other than dict you must set the safe parameter to False :

response = JsonResponse([1, 2, 3], safe=False)

After days of beating my head against a wall, I chose to go with a different implementation. It appears I can only render the data on the page that initially sent the request.

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