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

时间:2013-10-16 13:39:13

标签: jquery ajax json

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

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

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

像jqXHR.message?

非常感谢你的帮助......

EDIt:

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

返回:

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

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

编辑:此代码有效:

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

1 个答案:

答案 0 :(得分:48)

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

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

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