jQuery 获取带有 AJAX 错误的服务器响应?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19405033/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 23:53:19  来源:igfitidea点击:

Get server response with AJAX error?

jqueryajaxjson

提问by Ziplo

for an incorrect Ajax action, I set with HTTP header code to 403 and send the following response :

对于不正确的 Ajax 操作,我将 HTTP 标头代码设置为 403 并发送以下响应:

{"code":"403","status":"Forbidden","message":"You cannot do this"}

However, I can't access this data when handling my error... Is it possible to acess "message"data from jqXHR ?

但是,我在处理错误时无法访问此数据...是否可以从 jqXHR 访问“消息”数据?

something like jqXHR.message ?

类似 jqXHR.message 的东西?

Many thanks for your help...

非常感谢您的帮助...

EDIt :

编辑 :

error: function (xhr) {
            $(".alert").html(xhr.responseText);
          },

This returns :

这返回:

{"code":"403","status":"Forbidden","message":"You cannot do this"}

But xhr.responseText.message doesn't return anything ...

但是 xhr.responseText.message 没有返回任何东西......

EDIT : this code works :

编辑:此代码有效:

  error: function (xhr) {
    var jsonResponse = JSON.parse(xhr.responseText);
    $(".alert").html(jsonResponse.message);
  },

回答by sk8terboi87 ツ

You should be getting in jQuery 'error' callback... http://api.jquery.com/jQuery.ajax/

你应该进入 jQuery 'error' 回调...... http://api.jquery.com/jQuery.ajax/

 error: function(xhr, status, error) {
    alert(xhr.responseText);
 }

(btw.. ur code?)

(顺便说一句......你的代码?)