从http.post获取返回值

时间:2019-04-27 20:29:11

标签: angularjs

我的问题是以下我在这里有此代码:

$http.post("dologin", data).then(function(resposta)

当我提供console.log(response.data)时,它返回以下内容:

 string(40) "7f9870111b7c032f6203d144c97b8aa5a3e3f0c5"
 {"status":"success","type_user":"secretary"}

我需要获取“状态”值。在我使用以下内容之前,它工作正常

if (response.data.status === 'success') {
    if (answer.data.type_user === 'teacher') {
      $ location.path ('teacher_view');
    } else if (response.data.type_user === 'candidate') {
      $ location.path ('candidate_view');
    } else if (answer.data.type_user === 'secretary') {
      $ location.path ('secretaria_view');
    }

现在它不再起作用,当我提供console.log(response.data.status)时;它返回未定义的

我的后端php

    public function do_login(){
     $this->load->model('LoginM');
     $request_body = file_get_contents('php://input');
 $data = json_decode($request_body);
 $cpf = trim($data->cpf);
 $senha = trim($data->senha);
     $tipo = trim($data->tipo);

 $response = $this->LoginM->do_login($cpf, $senha, $tipo);

 if ($response["status"] === "success"){
        if ($tipo == 'admin') {
     $data = array(
         'logged_in' => true,
         'cod_user' => $response["cod_user"]
     );
     $message = array("status"=>"success", "tipo_user"=>"secretaria");
     }elseif ($tipo == 'professor') {
     $data = array(
         'logged_in' => true,
         'cod_professor' => $response["cod_professor"]
     );
     $message = array("status"=>"success", "tipo_user"=>"professor");
    }elseif ($tipo == 'candidato') {
     $data = array(
         'logged_in' => true,
         'cod_candidato' => $response["cod_candidato"]
     );
     $message = array("status"=>"success", "tipo_user"=>"candidato");
    }
   $this->session->set_userdata($data);
 }else{
   $message = array("status"=>"error","message"=>"CPF ou senha incorretos");
 }
 echo json_encode ($message);
}

使用console.log(response.data)和console.log(response.data.status)的响应进行测试

Image console.log

1 个答案:

答案 0 :(得分:1)

下面的事情应该可以解决这个问题:

var state = JSON.parse('{'+res.data.split("{")[1]);

if (state.status === 'success') {
 if (state.type_user === 'teacher') {
  $ location.path ('teacher_view');
 } else if (state.type_user === 'candidate') {
  $ location.path ('candidate_view');
 } else if (state.type_user === 'secretary') {
  $ location.path ('secretaria_view');
}

但是,我强烈建议您将服务器响应从您现在获取的字符串修复为您之前获取的JSON

相关问题