A
A
Alex2019-08-23 13:15:05
JavaScript
Alex, 2019-08-23 13:15:05

How to get data from django with ajax?

Good afternoon. So, I am getting data to the server after clicking a button using ajax. The data comes, but I didn’t quite understand how to form the answer.

jQuery:

$.ajax({
        url: '/sorter/',

        type: "get",

        data: {
          'k': 1
        },

        dataType: 'text',

        success: function(data){
          console.log(data);
        }
      }
    );


Django:
def sorter(request):
    if request.method == 'GET':
        return HttpResponse('1')
    else:
        return redirect('http://127.0.0.1:8000')

Please explain what I am doing wrong.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
szelga, 2019-08-23
@szelga

something like this:

from django.http import JsonResponse

def sorter(request):
    if request.method == 'GET':
        return JsonResponse('1')
    else:
        return redirect('http://127.0.0.1:8000')

so that, in particular, returns Content-Typeapplication/json.
if you need a lot of Ajax, then it's better to use a library like DRF or tastypie.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question