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

时间:2013-05-29 11:39:20

标签: php javascript jquery ajax cakephp

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

$.ajax({
            type: 'POST',
            url: $form.attr('action'),
            data: formData,
            dataType: 'json',
            success: function(data){
                console.log(data.id);
           },
            error: function(message){
                console.log(message.code);
           }
       });

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

public function login() {
        if ($this->request->is('post')) {
            if ($this->Auth->login()) {
                return new CakeResponse(array('body'=> json_encode(
                                        $this->Auth->user()),'status'=>200));

            } else {
                $reply["code"] = "Invalid username or 
                                  password and please try again";
                return new CakeResponse
                (array('body'=> json_encode($reply),'status'=>500));
            }
        }
    }

问题是,当服务器发送错误时,我无法读取json响应。下面剪切的console.log应该写“无效的用户名或密码,请再试一次”,但它说取消定义。

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

但是,我能够阅读以下内容:

success: function(data){
                console.log(data.id);
           }

2 个答案:

答案 0 :(得分:3)

jQuery error回调的参数描述为here

所以第一个参数是jqXHR对象,描述为here

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

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

答案 1 :(得分:1)

在下面的代码中:

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

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

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