我如何在没有模板的Django中发送空响应 [英] How do I send empty response in Django without templates

查看:87
本文介绍了我如何在没有模板的Django中发送空响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写了一个视图,该视图响应来自浏览器的ajax请求.它是这样写的-

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.

我该怎么做?

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

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

推荐答案

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

render_to_response is a shortcut specifically for rendering a template. If you don't want to do that, just return an empty HttpResponse:

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

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

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.

这篇关于我如何在没有模板的Django中发送空响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆