【问题标题】:How do I send empty response in Django without templates如何在没有模板的情况下在 Django 中发送空响应
【发布时间】:2011-05-06 14:34:58
【问题描述】:

我编写了一个视图来响应来自浏览器的 ajax 请求。是这样写的——

@login_required
def no_response(request):
    params = request.has_key("params")
    if params:
        # do processing
        var = RequestContext(request, {vars})
        return render_to_response('some_template.html', var)
    else: #some error
        # I want to send an empty string so that the 
        # client-side javascript can display some error string. 
        return render_to_response("") #this throws an error without a template.

我该怎么做?

这是我在客户端处理服务器响应的方式 -

    $.ajax
    ({
        type     : "GET",
        url      : url_sr,
        dataType : "html",
        cache    : false,
        success  : function(response)
        {
            if(response)
                $("#resp").html(response);
            else
                $("#resp").html("<div id='no'>No data</div>");
        }
    });

【问题讨论】:

    标签: python ajax django django-views


    【解决方案1】:

    render_to_response 是专门用于渲染模板的快捷方式。如果您不想这样做,只需返回一个空的HttpResponse

     from django.http import HttpResponse
     return HttpResponse('')
    

    但是,在这种情况下,我不会这样做 - 您是在向 AJAX 发出错误信号,因此您应该返回错误响应,可能是代码 400 - 您可以使用 HttpResponseBadRequest 代替.

    【讨论】:

      【解决方案2】:

      我认为返回空响应的最佳代码是204 No Content

      from django.http import HttpResponse
      return HttpResponse(status=204)
      

      但是,在您的情况下,您不应返回空响应,因为 204 表示:The server *successfully* processed the request and is not returning any content.

      最好返回一些4xx 状态代码以更好地表明错误是in the client side。你可以在4xx 响应的正文中放入任何字符串,但我强烈建议您发送JSONResponse

      from django.http import JsonResponse
      return JsonResponse({'error':'something bad'},status=400)
      

      【讨论】:

        猜你喜欢
        • 2021-09-03
        • 2012-10-29
        • 2011-06-22
        • 1970-01-01
        • 2013-05-08
        • 2010-09-11
        • 2017-04-10
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多