Javascript在读取cakephp发送的json服务器错误响应后表示未定义


Javascript says undefined after reading json server error response sent by cakephp

下面是我的AJAX方法,它能够连接到服务器:

<>之前. ajax({美元类型:"文章",url: $ form.attr('行动'),数据:formData,数据类型:json,成功:功能(数据){console.log (data.id);},错误:函数(消息){console.log (message.code);}});之前

下面是我为cakephp UsersController类创建的响应请求的方法:

<>之前公共函数login() {If ($this->request->is('post')) {if ($this->Auth->login()) {array('body'=> json_encode()$ this -> Auth ->用户()),"地位"=> 200));} else {$reply["code"] = "无效的用户名或输入密码,请重试";返回新的cakeerresponse(数组("身体"=> json_encode(回复美元),"地位"=> 500));}}}之前

问题是,当服务器发送错误时我无法读取json响应。下面的控制台日志应该写"无效的用户名或密码,请再试一次",但它说未定义。

<>之前错误:函数(消息){console.log (message.code);} 之前

然而,我能读到以下内容:

<>之前成功:功能(数据){console.log (data.id);}

jQuery error回调的参数描述如下:

第一个参数是jqXHR对象,如下所示:

所以我猜你可以读它的responseText属性。

error: function(jqXHR, textStatus, errorThrown) {
    var message = JSON.parse(jqXHR.responseText);
    console.log(message.code);
}

在你的代码中:

error: function(message){
      console.log(message.code);
}

您将获得服务器发送的错误,而不是您试图从代码中获取的错误。从服务器端读取错误。使用下面的代码:

error: function(message,err,xtr){
      console.log(JSON.stringify(message)+" "+err+ " " +xtr);
}