如何从 ajax 错误响应中提取 responseText?
How to extract responseText from ajax error response?
在我的 go http 处理函数响应 ajax 请求中,我想发送这样的错误消息:
func AddBlogPOST(w http.ResponseWriter, r *http.Request) {
//process request
if everythingIsOk(r) {
w.Write([]byte("ok"))
return
} else {
w.WriteHeader(http.StatusUnauthorized)
w.Write([]byte("not enough credit"))
return
}
ajax请求是这样的:
$(document).on('click', '#submit', function (e) {
$.ajax({
url: '/blog/',
type: 'post',
data: $('.form').serialize(),
success: (res) => {
console.log('success body:', res);
console.log(res);
},
error: (err) => {
console.log('an error occured:', err);
}
});
}
});
当 reuqest 成功并且我在浏览器控制台中得到 success body: ok
时它工作正常。但是,当出现错误时,我会得到一个像这样的对象:
readyState: 4, getResponseHeader: ƒ, getAllResponseHeaders: ƒ, setRequestHeader: ƒ, overrideMimeType: ƒ, …}
abort: ƒ (e)
always: ƒ ()
catch: ƒ (e)
done: ƒ ()
fail: ƒ ()
getAllResponseHeaders: ƒ ()
getResponseHeader: ƒ (e)
overrideMimeType: ƒ (e)
pipe: ƒ ()
progress: ƒ ()
promise: ƒ (e)
readyState: 4
responseText: "credit not enough"
setRequestHeader: ƒ (e,t)
state: ƒ ()
status: 401
statusCode: ƒ (e)
statusText: "Unauthorized"
then: ƒ (t,n,r)
如何从此对象中提取 "credit not enough"
?
您的 error
处理程序中名为 err
的参数是 jqXHR 对象。要从您的服务器端代码中检索您 return 的错误消息,您需要手动访问该对象的 responseText
属性。试试这个:
error: (jqXHR) => {
console.log('an error occurred:', jqXHR.responseText);
}
在我的 go http 处理函数响应 ajax 请求中,我想发送这样的错误消息:
func AddBlogPOST(w http.ResponseWriter, r *http.Request) {
//process request
if everythingIsOk(r) {
w.Write([]byte("ok"))
return
} else {
w.WriteHeader(http.StatusUnauthorized)
w.Write([]byte("not enough credit"))
return
}
ajax请求是这样的:
$(document).on('click', '#submit', function (e) {
$.ajax({
url: '/blog/',
type: 'post',
data: $('.form').serialize(),
success: (res) => {
console.log('success body:', res);
console.log(res);
},
error: (err) => {
console.log('an error occured:', err);
}
});
}
});
当 reuqest 成功并且我在浏览器控制台中得到 success body: ok
时它工作正常。但是,当出现错误时,我会得到一个像这样的对象:
readyState: 4, getResponseHeader: ƒ, getAllResponseHeaders: ƒ, setRequestHeader: ƒ, overrideMimeType: ƒ, …}
abort: ƒ (e)
always: ƒ ()
catch: ƒ (e)
done: ƒ ()
fail: ƒ ()
getAllResponseHeaders: ƒ ()
getResponseHeader: ƒ (e)
overrideMimeType: ƒ (e)
pipe: ƒ ()
progress: ƒ ()
promise: ƒ (e)
readyState: 4
responseText: "credit not enough"
setRequestHeader: ƒ (e,t)
state: ƒ ()
status: 401
statusCode: ƒ (e)
statusText: "Unauthorized"
then: ƒ (t,n,r)
如何从此对象中提取 "credit not enough"
?
您的 error
处理程序中名为 err
的参数是 jqXHR 对象。要从您的服务器端代码中检索您 return 的错误消息,您需要手动访问该对象的 responseText
属性。试试这个:
error: (jqXHR) => {
console.log('an error occurred:', jqXHR.responseText);
}