如何在没有模板的 Django 中发送空响应
我编写了一个响应来自浏览器的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>");
}
});
I have written a view which responds to ajax requests from browser. It's written like so -
@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.
How do i do it?
Here's how I handle the server response on client-side -
$.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>");
}
});
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
render_to_response
是专门用于渲染模板的快捷方式。如果您不想这样做,只需返回一个空的HttpResponse
:但是,在这种情况下我不会这样做 - 您向 AJAX 发出信号表明存在错误,因此您应该返回一个错误响应,可能是代码 400 - 您可以使用
HttpResponseBadRequest
来代替。render_to_response
is a shortcut specifically for rendering a template. If you don't want to do that, just return an emptyHttpResponse
:However, in this circumstance I wouldn't do that - you're signalling to the AJAX that there was an error, so you should return an error response, possibly code 400 - which you can do by using
HttpResponseBadRequest
instead.我认为返回空响应的最佳代码是
204 No Content
。但是,在您的情况下,您不应返回空响应,因为 204 表示:
服务器*成功*处理了请求并且没有返回任何内容。
。最好返回一些
4xx
状态代码,以更好地表明错误位于 客户端。您可以在4xx
响应正文中放置任何字符串,但我强烈建议您发送JSONResponse
:I think the best code to return an empty response is
204 No Content
.However, in your case, you should not return an empty response, since 204 means:
The server *successfully* processed the request and is not returning any content.
.It is better returning some
4xx
status code to better signal the error is in the client side. Yo can put any string in the body of the4xx
response, but I highly recommend you send aJSONResponse
: