作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
这是我的代码:
$.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);
});
请求:
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":...
请求正文实际上是一个有效的 json,为了简洁起见,我只是将其截断。
响应:
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": [
{...
同样,响应是一个完全有效的 json,为简洁起见被截断。
正如预期的那样,使用 err
对象调用 error
处理程序。但是,如何才能获取解析后的 json 呢?当然,我可以检查响应的内容类型是否为 json,然后自己解析 err.responseText,但这不是 jQuery ajax 应该为我做的吗?我的意思是,当我从服务器获取对象时,它会对我的 $.get
查询执行此操作。
我错过了什么?
编辑
这是对 https://stackoverflow.com/a/12310751/80002 的更正:
执行请求:
var ajax = $.ajax(...
处理错误响应:
var res, ct = ajax.getResponseHeader("content-type") || '';
if (ct.indexOf('json') > -1) {
res = $.parseJSON(err.responseText);
// process the response here
}
最佳答案
我遇到了同样的问题,并发现了与@Barmar的答案略有不同的方法。
除了 responseText
之外,还有一个 responseJSON
属性,因此您可以执行以下操作:
var json_response = err.responseJSON.msg;
如果您console.log(err);
,您可能希望在页面上的错误消息中使用其中的一些属性。
关于jquery - 如何让 jQuery 解析表示为有效 json 的错误响应?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12310702/
我是一名优秀的程序员,十分优秀!