是否可以使用text和json对象返回django中的HttpResponse?

Har*_*ikh 12 django httpresponse django-views

在我的视图函数中,我想返回一个json对象(data1)和一些text/html(form).这可能吗?

这是我的views.py的一部分:

if request.is_ajax() and request.method == 'POST':
...
    if form.is_valid():
        answer = form.cleaned_data['answer'] # Answer extracted from form is also a string
        a1 = ques1.correct_answer
                    if a1 == answer:
            test1 = question_list.get(id=nextid)
            form = AnswerForm(test1)
            ques1 = question_list.filter(id=nextid)                     # Filter next question as <qs>
            data1 = serializers.serialize("json",ques1)                 # Json-ize
    # ********EDITED HERE **********        
            variables1 = Context({
                'form' : form,
                'q1'   : data1,
            })  
            #response = HttpResponse()
            #response['data1'] = response.write(data1)
            #response['form'] = response.write(form) 
            if nextid <= qsnlen:
                return HttpResponse(variables1, mimetype="application/json")
                #return HttpResponse(response)
            else:
...
Run Code Online (Sandbox Code Playgroud)

我想发送回形式html和ques1 json对象.我怎样才能做到这一点?提前致谢.

Ada*_*mKG 11

只需将两个数据放在一个JSON容器中,一个键用表单数据,一个用HTML作为渲染字符串.在浏览器中,您可以将两个键拉出来并完成您的工作.

在你看来:

form_json_data = get_form_json_data()
rendered_html = get_the_html()
return HttpResponse(json.dumps({
        "formdata": form_json, 
        "html": rendered_html}),
    content_type="application/json")
Run Code Online (Sandbox Code Playgroud)

在js中:

$.post(foo, postdata, function(data){
    var formdata = data.formdata
    var html = data.html;
    $(".html-target").replaceWith(html);
    do_whatever(formdata);
})
Run Code Online (Sandbox Code Playgroud)

  • 好吧,你不能JSON序列化Python对象.你不能发送'问题对象'本身; 你只能发送对象属性的JSON字典.Django有一个[内置序列化帮助器](https://docs.djangoproject.com/en/dev/topics/serialization/#serializing-data),可以处理查询集. (2认同)

i_e*_*uel 6

使用JsonResponse

from django.http import JsonResponse
response_data = {put your data into a dict}
return JsonResponse(response_data, status=201)
Run Code Online (Sandbox Code Playgroud)


Bur*_*lid 0

只需一个响应即可完成此操作;您需要在模板响应 (HTML) 的上下文中以纯文本形式发送 JSON。

如果您需要将 JSON 作为单独的 JSON 对象发送,并具有自己的 mime 类型,那么您需要编写两个视图;发送回 JSON 的方法为application/json and the other that sends back the form (HTML).

编辑:

您没有返回 JSON 对象,而是正在转换一个包含两种不同类型的两个项目的字典。正如我在评论中所解释的,在一个请求/响应周期中;您只能返回一个具有特定 mime 类型的响应,该类型基于内容以及您希望浏览器处理它的方式。大多数时候内容类型是'text/html'.

在您的场景中,如果您想要返回 HTML(这是您的表单)和 JSON 响应(这是一个字符串),则需要返回 HTML。

如果你想将JSON作为JSON对象返回给Jquery;您需要检测请求类型。在前端(模板)中,您将发起两个请求 - 一个来自浏览器,该请求将返回表单。另一个来自 jQuery,它将返回适当的 JSON 对象。

这是一种可能的方法:

  def foo(request):
     if request.is_ajax():
        ctx = dict()
        ctx['hello'] = 'world'
        return HttpResponse(json.dumps(ctx),content_type='application/json')
     else:
        return HttpResponse('hello world')
Run Code Online (Sandbox Code Playgroud)