使用AJAX错误获取服务器响应?

Zip*_*plo 24 ajax jquery json

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

{"code":"403","status":"Forbidden","message":"You cannot do this"}
Run Code Online (Sandbox Code Playgroud)

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

像jqXHR.message这样的东西?

非常感谢您的帮助...

EDIt:

error: function (xhr) {
            $(".alert").html(xhr.responseText);
          },
Run Code Online (Sandbox Code Playgroud)

返回:

{"code":"403","status":"Forbidden","message":"You cannot do this"}
Run Code Online (Sandbox Code Playgroud)

但是xhr.responseText.message没有返回任何内容......

编辑:此代码有效:

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

sk8*_* ツ 49

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

 error: function(xhr, status, error) {
    alert(xhr.responseText);
 }
Run Code Online (Sandbox Code Playgroud)

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

  • 我将"未定义"视为警报消息 (10认同)