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

查看:36
本文介绍了如何在没有模板的情况下在 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天全站免登陆