2012-05-11 3 views
0

codeigniter보기에서 json 데이터를 반환하려고합니다. 하지만 내 코드가 작동하지 않습니다. 나는이 사이트에서 주어진 모든 옵션을 시도했습니다. 하지만 난보기에서 json 데이터를 반환 할 수 없습니다 이것은 컨트롤러 코드입니다.codeginiter json 출력 오류

<?php 
class Json extends CI_Controller 
{ 

    function __construct() 
    { 
     parent::__construct(); 

    } 
    public function index() 
    { 
     $this->load->model('get_json'); 
     $data['message']=$this->get_json->get_fruits(); 

     if ($data!== false) 
     { 
        $this->load->view('json',json_encode($data['message'])); 
     } 
    } 
} 

내 모델

<?php 

    class get_json extends CI_Model 
    { 
     function __construct() 
     { 
      parent::__construct(); 
     } 


     function get_fruits() 
     { 
      $sql = "SELECT * FROM fruit where name='Apple'"; 
      $query = $this->db->query($sql); 
      // Fetch the result array from the result object and return it 
      return $query->result(); 

     } 

    } 

보기 코드 :

<?php 
$this->output->set_content_type('application/json'); 
echo $message; 

내 코드가 잘못 wwhere 도와주세요. 이것에

ERROR - 2012-05-11 15:28:40 --> Severity: Notice --> Undefined variable: message C:\xampp\htdocs\ci\system\core\Loader.php(829) : eval()'d code 3 
DEBUG - 2012-05-11 15:28:40 --> File loaded: application/views/json.php 

답변

3

변경 컨트롤러 index 방법 :

public function index() 
    { 
     $this->load->model('get_json'); 
     $data['message']= json_encode($this->get_json->get_fruits()); 

     if ($data!== false) 
     { 
        $this->load->view('json',$data); 
     } 
} 

을 그리고 당신은 갈 수 있어야한다 : 당신의 배열을 전달해야

는 스피 나의 로그에 얻는 것입니다 $this->load->view, 인코딩 된 값이 아닙니다.

EDIT : 사이드 노트로서, 이런 종류의 일을하기 위해서는 뷰가 필요하지 않습니다. 당신은 컨트롤러에서 직접 결과를 반환 할 수 있습니다

public function index() 
    { 
     $this->load->model('get_json'); 
     $message = $this->get_json->get_fruits(); 

     if ($message !== false) 
     { 
        $this->output->set_content_type('application/json'); 
        echo json_encode($message); 
     } 
} 

클리너, 한 곳에서 모든 것을두고, 약간 더 효율적입니다.

+0

+1 정보는보기에 적합하지 않습니다. 내 컨트롤러의 – gorelative

+0

에코가 작동하지 않습니다. iam은 여전히 ​​수정을 찾았습니다. [link] http://stackoverflow.com/questions/10520423/echo-in-codeignter-controller-is-not-working [/ link] – user1130639

+0

+1 좋은 답변입니다. – Adam