简体   繁体   English

如何将AJAX JSON发布请求从Jquery转换为Python / Django字典

[英]How to convert ajax json post request from Jquery to Python/Django dictionary

I am trying to convert an AJAX request retrieving JSON from JS to Python's dictionary in Django, but unsuccessfully. 我正在尝试将从JSON检索JSON的AJAX请求转换为Django中的Python字典,但未成功。 Please help. 请帮忙。

This is the original JS code: 这是原始的JS代码:

myJSON = JSON.stringify(myJsObject);

// POST - send JSON data to Python/Django server
$.ajax({
  url: "/savemyexposuresituation",
  type: "POST",
  datatype: 'json',
  data: myJSON,
  async: false,
  success: function() {
    alert('Your data is saved :)');
  },
  error: function() {
    alert('Error occured :(');
  }
});
}

This is the Django side: 这是Django方面:

def saveExposureSituation(request):

#get es data - JSON file
fromJs = request.POST

fromJs = json.loads(fromJs)

All I get is JSON object must be string, not QueryDict . 我得到的只是JSON object must be string, not QueryDict I tried to convert this QueryDict to something else unsuccessfully. 我试图将此QueryDict转换为其他错误。

request.POST is for form-encoded data. request.POST用于表单编码的数据。 You should be using request.body . 您应该使用request.body

In python 3 to convert byte to strings you need to use decode("utf-8") . 在python 3中将字节转换为字符串,您需要使用decode("utf-8") So may be to something like this request.POST.decode("utf-8") 可能是这样的request.POST.decode("utf-8")

Thanks to responses, the complete answer would be: 感谢您的答复,完整的答案将是:

def saveExposureSituation(request):

    fromJs = request.body
    fromJs = fromJs.encode('utf-8')

    #now we can load our JSON from JS
    fromJs = json.loads(fromJs)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM