2010-11-08 111 views
33

我写了一个响应来自浏览器的ajax请求的视图。它是这样写的 -如何在没有模板的情况下在Django中发送空响应

@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>"); 
     } 
    }); 

回答

58

render_to_response是呈现模板专门的快捷方式。如果你不想这样做,只是返回一个空HttpResponse

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

然而,在这种情况下我也不会做 - 你信令的AJAX,有一个错误,所以你应该返回一个错误响应,可能代码为400 - 您可以使用HttpResponseBadRequest来代替。

+0

爽哦!简单,所以我的问题原来是非常基本的!无论如何感谢您的帮助。今天学到了新东西。 – 2010-11-08 11:15:07

9

我认为返回空响应的最佳代码是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) 
相关问题