【发布时间】:2016-10-10 14:52:44
【问题描述】:
我有这个 Ajax 请求:
$.ajax({
url: "my_url",
headers: {'X-CSRFToken': '{{ csrf_token }}'},
type: "post",
data:{x:1
},
success: function(response, textStatus, xhr) {
alert(response + textStatus + xhr);
},
error: function(xhr, ajaxOptions, thrownError) {
alert(xhr.status + ' Error: ' + thrownError);
}
});
}
在 Django 方面,我有时想传播错误。
如果我引发异常,它将作为 500 响应内部错误传播。
但我想显示一条错误消息。
所以我尝试了
return HttpResponse("Bad permissions", status=500)
但我无法捕获自定义错误消息。 有什么想法吗?
对于那些想知道什么有效的人:
模板中的Javascript
function send(){
$.ajax({
url: "/get_pens/",
headers: {'X-CSRFToken': '{{ csrf_token }}'},
type: "post",
data:{x:1
},
dataType: "json",
success: function(response, textStatus, xhr) {
alert('Success: ' + response + textStatus + xhr);
},
error: function(xhr, ajaxOptions, thrownError) {
alert(xhr.status + ' Error: ' + xhr.responseJSON['err']);
}
});
}
views.py
>def get_pens(request):
pens = []
response = HttpResponse(json.dumps({'pens': pens, 'err': 'some custom error message'}),
content_type='application/json')
response.status_code = 400
return response
【问题讨论】:
-
你不能只发送一个像
{'status': 'success'}或{'status': 'the custom error message'}这样的json并在status不是success时显示错误消息吗? -
500 在这里并不合适。这要么是错误请求 (400),要么是无效权限的特定情况下,403。请参阅 here
-
您是否捕捉正在发生的异常?除非您这样做,否则它永远不会到达您的
HttpResponse或您正在使用的任何东西。 -
我可以发送一个响应,例如一个 json 响应并检查是否有错误键,但这听起来像是一个错误的方法。我认为正确的方法应该是使用响应状态,但我不知道如何。
-
alert(....)works。但是您是否尝试将消息添加到 div$('#some-id').html(xhr.responseJSON['err'])?