我已经写了一个视图来响应来自浏览器的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>");
        }
    });

推荐答案

render_to_response是专门用于渲染模板的快捷键.如果您不想这样做,只需返回一个空HttpResponse即可:

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

然而,在这种情况下,我不会这样做-您在向Ajax发出错误的信号,因此您应该返回一个错误响应(可能是代码400)-您可以使用HttpResponseBadRequest来实现这一点.

Django相关问答推荐

Django的update_or_create失败,尽管指定了kwargs'

Django www.example.com从常量列表中删除值

我的Django终结点不访问HAS_OBJECT_PERMISSION方法

基于Django类的视图:除非登录,否则拒绝访问future 日期

try 获取静态文件路径时 Django 给出错误

如何在 Fargate 容器中运行的 Django 中使用 AWS SES?

如何根据查询集中的条件返回多个聚合?

Django - 将 HTML 输出转换为变量

Django rest框架覆盖ViewSet中的page_size

Apache + mod_wsgi 与 nginx + gunicorn

在 Django 中获取下一个和上一个对象

Matplotlib - Tcl_AsyncDelete:异步处理程序被错误的线程删除?

django 管理列表中的外键显示

如何从 Django 的 TabularInline 管理视图中省略对象名称?

Django中的自定义排序

如何使用查询参数构造 Django 反向/url?

ProgrammingError: 安装 Psycopg2 后,关系django_session不存在错误

Django 在视图之间传递数据

如何动态访问 Django 模型字段详细名称?

django.urls.path中name参数的作用是什么?