如何让 jQuery 解析表示为有效 json 的错误响应?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12310702/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to make jQuery parse my error response represented as a valid json?
提问by mark
Here is my code:
这是我的代码:
$.ajax({
url: "/api/invoice/" + newInvoice._id,
type: 'PUT',
data: JSON.stringify(newInvoice),
dataType: 'json',
contentType: "application/json; charset=utf-8"
})
.success(function () {
$('#statusLine').text('Successfully submitted invoice {0}. Click here to dismiss.'.format(newInvoice._id));
})
.error(function (err) {
alert(err);
});
The request:
请求:
PUT http://localhost:8000/api/invoice/16211 HTTP/1.1
Host: localhost:8000
Connection: keep-alive
Content-Length: 770
Origin: http://localhost:8000
X-Requested-With: XMLHttpRequest
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/536.11 (KHTML, like Gecko) Chrome/20.0.1132.57 Safari/536.11
Content-Type: application/json; charset=UTF-8
Accept: application/json, text/javascript, */*; q=0.01
Referer: http://localhost:8000/invoice.html?id=16211
Accept-Encoding: gzip,deflate,sdch
Accept-Language: fr-FR,fr;q=0.8,en-US;q=0.6,en;q=0.4
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3
{"items":[{"id":...
The request body is actually a valid json, I have just truncated it for brevity.
请求正文实际上是一个有效的 json,为了简洁起见,我只是将其截断了。
The response:
响应:
HTTP/1.1 409 Conflict
X-Powered-By: Express
Content-Type: application/json; charset=utf-8
Content-Length: 1386
ETag: 250542419
Connection: keep-alive
{
"msg": "Cannot update the invoice #16211, because it has already been updated by someone else.",
"invoice": {
"items": [
{...
Again, the response is a completely valid json, truncated for brevity.
同样,响应是一个完全有效的 json,为简洁起见被截断。
As expected, the error
handler is invoked with the err
object. However, how can I get hold on the parsed json? Of course, I could check that the content-type of the response is json and then parse the err.responseText
myself, but isn't it what jQuery ajax is supposed to do for me? I mean, it does so for my $.get
queries when I get the objects from the server.
正如预期的那样,error
处理程序是用err
对象调用的。但是,我怎样才能掌握解析的 json 呢?当然,我可以检查响应的内容类型是 json 然后err.responseText
自己解析,但这不是 jQuery ajax 应该为我做的吗?我的意思是,$.get
当我从服务器获取对象时,它会为我的查询执行此操作。
What am I missing?
我错过了什么?
EDIT
编辑
This is a correction to https://stackoverflow.com/a/12310751/80002:
这是对https://stackoverflow.com/a/12310751/80002的更正:
Doing the request:
执行请求:
var ajax = $.ajax(...
Processing the error response:
处理错误响应:
var res, ct = ajax.getResponseHeader("content-type") || '';
if (ct.indexOf('json') > -1) {
res = $.parseJSON(err.responseText);
// process the response here
}
回答by martincarlin87
I ran into the same issue and found a slightly different way from @Barmar's answer.
我遇到了同样的问题,发现与@Barmar 的回答略有不同。
Aswell as responseText
, there is also a responseJSON
property, so you could do the following:
除了responseText
,还有一个responseJSON
属性,因此您可以执行以下操作:
var json_response = err.responseJSON.msg;
If you console.log(err);
there's a few properties in there that you might wish to use in your error message on the page.
如果您console.log(err);
有一些属性,您可能希望在页面上的错误消息中使用。
回答by Joel Purra
For an error message with a non-2001HTTP status code, the content will not be parsed by jQuery. If you'd really like not to parse the returned result to JSON yourself, you would have to return a HTTP status 200 and use the success
(done
) callbacks.
对于非 200 1 HTTP 状态代码的错误消息,jQuery 不会解析内容。如果您真的不想自己将返回的结果解析为 JSON,则必须返回 HTTP 状态 200 并使用success
( done
) 回调。
It's a good sign that you're using (from your example) HTTP code 409, and I think you should keep doing that - just bite the bullet and parse the JSON manually in your error handler. If the parsing fails, something else has gone wrong (like a temporary network failure), but this will allow you to build a nice API that you (and possibly others) can consume without having to build too much error checking into the success function.
这是一个好兆头,您正在使用(从您的示例中)HTTP 代码 409,我认为您应该继续这样做 - 只是硬着头皮在错误处理程序中手动解析 JSON。如果解析失败,则说明出现了其他问题(例如暂时的网络故障),但这将允许您构建一个您(可能还有其他人)可以使用的不错的 API,而不必在成功函数中构建过多的错误检查。
Keep success
for the happy results, and error
for unhappy results.
保持success
快乐的结果,和error
不愉快的结果。
1Technically any 2xx status should be considered successful; in jQuery (status >= 200 && status < 300 || status === 304)
counts as something successful.
1从技术上讲,任何 2xx 状态都应被视为成功;在 jQuery 中(status >= 200 && status < 300 || status === 304)
算作成功的事情。
回答by Barmar
Call $.parseJSON
explicitly in your error callback:
呼叫$.parseJSON
你的错误回调明确:
(...)
.error(function (err) {
var msg = $.parseJSON(err).msg;
alert(msg);
});
回答by Smit Luvani
It's very simple to get a JSON format. It's already featured by jQuery.
获取 JSON 格式非常简单。它已经由 jQuery 提供。
var error = error.responseJSON