GET with AJAX (Fetch)

 

from django.views import View
from django.views.generic import TemplateView
from django.http import JsonResponse

class index(TemplateView):
    template_name = 'polls/index.html'


class get_param(View):
    def get(self, request, *args, **kwargs):
        param = request.GET.get('param')

        print(param)

        context = {}
        context['param'] = param
        context['message'] = 'Reply with some text!'

        return JsonResponse(context)

 

urlpatterns = [
    path("", index.as_view(), name="index"),
	path("get_param/", get_param.as_view(), name="get_param"),
]

 

<a href="/get_param?param=value1" onclick="loadData(event)">Value 1</a> <br>
<a href="/get_param?param=value2" onclick="loadData(event)">Value 2</a>

<script>
    function loadData(event) {
        event.preventDefault();  

        const href = event.target.getAttribute('href');

        fetch(href)
        .then(response => response.json())
        .then(data => console.log(data))  
        .catch(error => console.error('Error:', error));  
    }
</script>

 


 

 


Tested with Django 4.2



09 Sept. 2024 | Last Updated: 02 Dec. 2025 | jaimedcsilva

Related
  • GET (Query Parameters)
  • GET (URL Parameters)
  • GET with AJAX (Fetch)
  • POST
  • POST with AJAX (Fetch)

  • Buy Me a Coffee