2013-10-16 66 views
24

有不正確的阿賈克斯行動時,我的HTTP標頭代碼設置爲403,併發送如下回應:使用AJAX錯誤獲取服務器響應?

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

然而,處理我的錯誤,當我無法訪問此數據...是否可以接取來自jqXHR的「消息」數據?

像jqXHR.message?

非常感謝您的幫助...

編輯:

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

http://stackoverflow.com/q/1637019/ 139010雖然注意關於使用'JSON.parse()'而不是'eval'的評論。 –

+0

你有什麼編碼? – Satya

+0

應該是jsonResponse [「message」],不是? – jn29098

回答

46

你應該在jQuery的 '錯誤' 越來越回調... http://api.jquery.com/jQuery.ajax/

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

(順便說一句..我們的代碼?)

+9

我得到「未定義」作爲警報消息 –