Post方法正在获取字节而不是json d

2024-04-24 10:14:52 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在请求jquery在我的博客中发表一篇文章。你知道吗

//Responsible for creating an article 
$('#create-article').click(function(e){
    title = $('#input-title').val()
    description = $('#input-desc').val() 
    data = {title, description}
    $.post('/blog/create/', data, 'json')
    e.stopPropagation();
    e.preventDefault();
})

下面的视图负责打印POST响应。根据我的POST提交,它应该输出一个json响应,但它输出的是Python字节。为什么会这样?你知道吗

@csrf_exempt
def create_article(request):
    if request.POST:
        print(request.body)
        return HttpResponseRedirect(reverse('home'))

打印:b'title=hello+&;description=world+there'

应为:{'title':'hello','description':'world there'}

我应该怎么做才能得到预期的结果?你知道吗


Tags: jsonhelloworldinputdatatitlerequestcreate
1条回答
网友
1楼 · 发布于 2024-04-24 10:14:52

即使您指定希望服务器在AJAX调用中返回JSON,您仍然需要在后端处理JSON的返回。现在request.body只返回Python的默认值,而不是JSON。你知道吗

import json

@csrf_exempt
def create_article(request):
    if request.POST:
        print 'Content-Type: application/json\n'
        print(json.dumps(request.body))
        return HttpResponseRedirect(reverse('home'))

相关问题 更多 >