Sri*_*aju 47 python django ajax django-views
我写了一个视图,它响应来自浏览器的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.
Run Code Online (Sandbox Code Playgroud)
我该怎么做?
以下是我在客户端处理服务器响应的方法 -
$.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>");
}
});
Run Code Online (Sandbox Code Playgroud)
Dan*_*man 75
render_to_response是专门用于呈现模板的快捷方式.如果您不想这样做,只需返回一个空HttpResponse:
from django.http import HttpResponse
return HttpResponse('')
Run Code Online (Sandbox Code Playgroud)
但是,在这种情况下我不会这样做 - 你向AJAX发出错误信号,所以你应该返回一个错误响应,可能是代码400 - 你可以通过使用它来做HttpResponseBadRequest.
rob*_*les 29
我认为返回空响应的最佳代码是204 No Content.
from django.http import HttpResponse
return HttpResponse(status=204)
Run Code Online (Sandbox Code Playgroud)
但是,在您的情况下,您不应该返回空响应,因为204表示:The server *successfully* processed the request and is not returning any content..
最好返回一些4xx状态代码,以便在客户端更好地发出错误信号.哟可以把任何字符串放在4xx响应的正文中,但我强烈建议你发送一个JSONResponse:
from django.http import JsonResponse
return JsonResponse({'error':'something bad'},status=400)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
37373 次 |
| 最近记录: |