从AJAX POST请求接收Django视图中的错误解析request.body

时间:2019-05-29 12:27:27

标签: javascript python ajax jsonb

当尝试解析json和更新db时,我收到json解码错误,大概是因为json字符串未正确清理吗?

示例结果

title=casdkj&paste%5B0%5D%5Barguments%5D%5Bcenter%5D%5B%5D=0&paste%5B0%5D%5Barguments%5D%5Bcenter%5D%5B%5D=0&paste%5B0%5D%5Barguments%5D%5Bradius%5D=0&paste%5B0%5D%5BtoString%5D=draw.circle&csrfmiddlewaretoken=JlcoPVmr1mexHy0GzKRRZNKNOIt1Z4M8mlafJSydBHo0sVP3q4yZdOUiDsZps9U0

AJAX代码段

          $.ajax({
            url: 'paste/',
            type: 'POST',
            headers:{
              "X-CSRFToken": getCookie('csrftoken')
            },
            // data: data,
            data: JSON.stringify(data),
            contentType: "application/json",
            complete: function(token) {

Django视图

def paste(request):
    if request.method == 'POST':
        body = json.loads(request.body.decode('utf-8'))

        p = Pastes.objects.create(
            title=body['title'],
            user=request.user.id,
            paste=body['paste']
        )
        p.save()

        return HttpResponse(
            json.dumps({'result': 'OK',}),
            content_type="application/json"
        )

错误

json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

0 个答案:

没有答案