2015-10-20 32 views
0

我有一個函數,我用它來獲取Auth組件的用戶ID。它工作正常,沒有使用return json_encode。問題是我需要這個與json_encode一起工作,因爲我從ajax請求獲取值。 使用json_encode它總是返回null id,我不明白爲什麼會發生。問題在於下面的功能indexAjax()

如何使用$this->Auth->user("id")json_encode並且它不返回空?

嘗試。

//using $this->set it works fine 
public function index() {  
       $id = $this->Auth->user("id");     
       $empresas = $this->Empresa->find('all', array(
          'fields'=>array("id", "nomeFantasia", "cnpj", 
            "telefone1", "telefone2", "celular", "aberto"), 
          'conditions'=>array("users_id = "=> $id)    
          ));    
       debug($id) or die; 
       //$this->set(compact('empresas')); 
    } 



//with json_encode always return null 
public function indexAjax() {  
       $this->autoRender = false; 
       $id = $this->Auth->user("id"); 
       $empresas = $this->Empresa->find('all', array(
          'fields'=>array("id", "nomeFantasia", "cnpj", 
            "telefone1", "telefone2", "celular", "aberto"), 
          'conditions'=>array("users_id = "=> $id)    
          )); 
       return json_encode($id);     
    } 

回答

0

解決了這個問題。我的解決方案是當用戶進行登錄我得到的用戶ID和寫入會話,所以當我需要這個ID我從會話直接而不是從AuthComponent。

它的工作原理。