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

时间:2022-10-08 23:39:57

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。口信吗?

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。消息没有返回任何东西…

EDIT : this code works :

编辑:此代码可以工作:

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

1 个解决方案

#1


47  

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?)

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

#1


47  

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?)

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