json transmission method based on Django and ajax

  • 2020-10-07 18:44:58
  • OfStack

When the front-end USES ajax for data interaction:


$.ajax({
 cache: false,
 type: "POST",
 url: {% url ''%}
 data: $('#form').serialize(),
 async: true,
 success: function (data) {
  if (data.status == 'success') {
   $('#form')[0].reset();
   alert(" Submitted successfully ")
  } else if (data.status == 'fail') {
   $('#tip').html(data.msg)
  }
 },
});

Background code:


if form.is_valid():
 
return HttpResponse("{'status':'success'}", content_type='application/json')

The background can receive data and return data to the front desk, but the front desk cannot parse it out.

When changing to the following, change the contents of json from single quotation marks to double quotation marks, and change the outer double quotation marks to single quotation marks, and the front end will parse normally


if form.is_valid():
 return HttpResponse('{"status":"success"}', content_type='application/json')

Visual inspection is due to a problem with the standard json format.


Related articles: