代码之家  ›  专栏  ›  技术社区  ›  Srikar Appalaraju Tonetel

如何在没有模板的Django中发送空响应

  •  41
  • Srikar Appalaraju Tonetel  · 技术社区  · 14 年前

    @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>");
            }
        });
    
    2 回复  |  直到 14 年前
        1
  •  77
  •   Daniel Roseman    14 年前

    render_to_response 是专门用于呈现模板的快捷方式。如果你不想这样做,就把一个空的 HttpResponse

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

    但是,在这种情况下,我不会这样做-您向AJAX发出错误的信号,所以您应该返回一个错误响应,可能是代码400-您可以使用 HttpResponseBadRequest 相反。

        2
  •  30
  •   robermorales    8 年前

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

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

    The server *successfully* processed the request and is not returning any content. .

    最好还一些 4xx 状态码以更好地指示错误是 in the client side 四倍 JSONResponse

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