登录
首页 >  Golang >  Go问答

如何从ajax错误响应中提取responseText?

来源:stackoverflow

时间:2024-04-13 23:12:41 262浏览 收藏

golang学习网今天将给大家带来《如何从ajax错误响应中提取responseText?》,感兴趣的朋友请继续看下去吧!以下内容将会涉及到等等知识点,如果你是正在学习Golang或者已经是大佬级别了,都非常欢迎也希望大家都能给我建议评论哈~希望能帮助到大家!

问题内容

在我的 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)

如何从该对象中提取“信用不足”


解决方案


error 处理程序中名为 err 的参数是 jqxhr 对象。要检索从服务器端代码返回的错误消息,您需要手动访问该对象的 responsetext 属性。试试这个:

error: (jqXHR) => {
  console.log('an error occurred:', jqXHR.responseText);
}

文中关于的知识介绍,希望对你的学习有所帮助!若是受益匪浅,那就动动鼠标收藏这篇《如何从ajax错误响应中提取responseText?》文章吧,也可关注golang学习网公众号了解相关技术文章。

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>