django post json ajax code example

Example 1: django ajax without jquery

from django.http import JsonResponse

def get_random_number_json(request):
    random_no = random.randint(1,100)
    return JsonResponse({'random_no': random_no})

Example 2: django ajax body to json

// From AJAX you need to post the data as JSON string rather than 
// a JavaScript object.
payload = JSON.stringify({"name": "foo", "username":"bar"})

$.ajax({
  url: 'some url',
  type: "POST",
  // ...
  data: payload,
  dataType: 'json',
  //..
})